0
votes

Getting the cors error when sending the request, but working in the postman

Error Message:

Access to fetch at (cloud function url) from origin (my web app) has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Cloud Function Code:

exports.add_edit_location_routes = functions.https.onRequest((request, response) => {
    let obj = request.body
    deletePreviousRoutes(obj.assign_route_id, obj.driver_id, () => addRoutes(obj, (msg) => {
        response.send(msg)
    }))
})

Request:

fetch("url", {
    body: JSON.stringify(json),
    method: "POST",
    headers: {'Content-Type': 'application/json'},
}).then(res => res.json()).then(obj => console.log(obj))

added this but still not working

res.set('Access-Control-Allow-Origin', '*')
1

1 Answers

2
votes

Try including the code you provided in the Cloud Function and not the fetch request.

exports.add_edit_location_routes = functions.https.onRequest((request, response) => {
  let obj = request.body
  response.set('Access-Control-Allow-Origin', '*')
  deletePreviousRoutes(obj.assign_route_id, obj.driver_id, () => addRoutes(obj, (msg) => {
      response.send(msg)
  }))
})