从前端到云功能的GET请求,可能吗?

时间:2020-07-11 10:02:06

标签: javascript google-cloud-platform axios

我正在尝试从JS前端向GCP云功能发出GET请求,但出现错误:


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).

我本来打算从前端调用第三方API,但它也给了我这个错误,然后我要看看是否可以将CF用作中间人,但我猜我需要设置服务器?

肯定有可能从前端向云功能或其他站点发出GET请求吗?

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)
})

3 个答案:

答案 0 :(得分:2)

这是浏览器安全策略,可避免意外请求。如果您是功能所有者,则需要为服务器设置白名单。

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!');
  }
};

此代码遵循GCP官方文件https://cloud.google.com/functions/docs/writing/http

答案 1 :(得分:1)

绝对有可能。您需要在云功能中允许您的来源。

另一方面,请尝试使用以下内容:

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)
})

答案 2 :(得分:0)

正如其他人所提到的,我可以在云函数中允许CORS,但这是使用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);
};

现在我可以从前端调用它了。