0

When i make a request to my api, chrome block my request cause of cores. On my firebase cloud function, i added response.set('Access-Control-Allow-Origin','*'); (xxxxxx in the axios get is just to hide the request url )

export const getApproximateAddress = functions.https.onRequest(async(request, response)=>{
 try{
     response.set('Access-Control-Allow-Origin','*');
     response.set('Access-Control-Allow-Methods','GET, POST, PATCH, PUT, DELETE, OPTIONS');
     let data = JSON.parse(request.body);
     let lat = "";
     let lng = "";
     let hasCoords = false;
     if( data.lat !== undefined && data.lng !== undefined){
         lat = data.lat;
         lng = data.lng;
         hasCoords = true;
     }
     let place = data.place;
     let result;
     if(hasCoords){
         result = await axios.get(`xxxxxxxx`);
         console.log("hehe");
     }else{
         result = await axios.get(`xxxxxxxx`);
     }
     if(result.status !== 200){
        response.status(result.status).send(result.data);
     }else{
        console.log(result.data.features);
        response.status(200).send(result.data.features);
     }
  }catch(error){
     response.status(500).send(error);
 }

});

then in my angular app, i make an http post request like this

searchLoation(query:any):Observable<any>{
  const url = 'https:XXXXXXXX/getApproximateAddress';
  return this.http.post(url,{place:query},{
    observe: 'body'
  });
}

the url is a different domain from where the request is coming from.

When i test everything in post man, everything works fine...

  • Did you allow CORS requests? – Maurice Pheyton Nov 27 '20 at 17:23
  • You're not implementing CORS correctly in your function. It will be easier if you use CORS middleware as illustrated in this other question. https://stackoverflow.com/questions/42755131/enabling-cors-in-cloud-functions-for-firebase – Doug Stevenson Nov 27 '20 at 17:28
  • at the begging of my function i added this response.set('Access-Control-Allow-Origin','*'); (refere to the first code snippet ) – civicboy 13 Nov 27 '20 at 17:29
  • @DougStevenson you were right, the mthod i used before to handle cors what not correct, i implemented const cors = require('cors')({ origin: true }); and wrapped the body of my function in cors(req, res, () => { function boy here }); and it worked – civicboy 13 Nov 27 '20 at 17:41
  • anyone know how i can update this question with the solution i found so that anyone having the same issue can use it ? – civicboy 13 Nov 27 '20 at 17:43

1 Answers1

0

You need to allow CORS on your server (in your cloud functions API). Probably something like this depending on what your API is built in. CORS always needs to be set on the server, the header usually will have no impact. Below is a node.js solution as an example. You will need to install the cors library

import * as cors from 'cors'

const app = express()

app.use(
  cors({
    origin: true,
  }),
)
omeanwell
  • 1,847
  • 1
  • 10
  • 16