1

I'm trying to make a GET request to a GCP Cloud Function from the frontend in JS, but I am getting the error:


Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-<project>.cloudfunctions.net/<function-name>. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I was originally going to call a 3rd party API from the front end but it gave me this error too, then I was going to see if I could use a CF as a middleman, but I'm guessing I'll need to set up a server?

Surely its possible to make a GET request from the frontend to a cloud function or other site?

axios({
    method: 'GET', //you can set what request you want to be
    url: "http://<cloud-function>.com/<function-name>",
    data: {message: "test"},
}).then(data => {
    console.log(data)
}).catch(error => {
    console.log(error)
})
UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
Ari
  • 5,301
  • 8
  • 46
  • 120

3 Answers3

3

This is browser security policy to avoid unexpected request. If you is owner of function, you need to setup a whitelist for your server.

exports.corsEnabledFunction = (req, res) => {
  // Set CORS headers for preflight requests
  // Allows GETs from any origin with the Content-Type header
  // and caches preflight response for 3600s

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

  if (req.method === 'OPTIONS') {
    // Send response to OPTIONS requests
    res.set('Access-Control-Allow-Methods', 'GET');
    res.set('Access-Control-Allow-Headers', 'Content-Type');
    res.set('Access-Control-Max-Age', '3600');
    res.status(204).send('');
  } else {
    res.send('Hello World!');
  }
};

This code is following GCP official document https://cloud.google.com/functions/docs/writing/http

rian
  • 370
  • 1
  • 6
1

It's possible definitely. You need to allow your origin in your cloud function.

On the other hand, please try to use the below:

axios({
    method: 'GET', //you can set what request you want to be
    url: "https://cors-anywhere.herokuapp.com/http://<cloud-function>.com/<function-name>",
    data: {message: "test"},
}).then(data => {
    console.log(data)
}).catch(error => {
    console.log(error)
})
critrange
  • 5,652
  • 2
  • 16
  • 47
0

As mentioned by others, I can allow CORS within the cloud function, but here is how to do so usng Nodejs:

exports.someFunction = (req, res) => {
  res.set('Access-Control-Allow-Origin', "*")
  res.set('Access-Control-Allow-Methods', 'GET, POST')
  res.set('Access-Control-Allow-Headers', 'Content-Type');

  let message = req.query.message || req.body.message || 'Hello World!';
  res.status(200).send(message);
};

Now I can call this from my frontend.

Ari
  • 5,301
  • 8
  • 46
  • 120