带有axios请求的Firebase云功能CORS错误

时间:2020-07-09 15:26:30

标签: javascript node.js firebase google-cloud-functions cors

我具有通用的云功能:

const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });

exports.helloWorld = functions.https.onRequest((request, response) => {
    cors(request, response, () => {
        res.status(200).send("Hello from Firebase!");
    });
});

我正在使用axios从客户端调用它:

  axios
    .get(
      "https://us-central1-dev-imcla.cloudfunctions.net/helloWorld",
    )
    .then((res) => {
      console.log(res);
    })
    .catch(er=>{
      console.log(er);
    })

我有2个问题:

  1. 我收到CORS错误。

在以下位置访问XMLHttpRequest 来自的“ https:// myurl / helloWorld” 来源'http:// localhost:8080'已被CORS政策阻止:否 请求中出现“ Access-Control-Allow-Origin”标头 资源。 xhr.js?b50d:178 GET https://us-central1-dev-imcla.cloudfunctions.net/helloWorld 净:: ERR_FAILED

  1. 如果我从浏览器打开了cors插件,或者如果我从邮递员调用了函数,则会出现此错误:

错误:禁止您的客户端无权获取URL / helloWorld从该服务器。

错误:请求失败,状态码为403 在createError(createError.js?2d83:16) 在解决时(settle.js?467f:17) 在XMLHttpRequest.handleLoad(xhr.js?b50d:61)

问题是我既是经过身份验证的用户,又在云代码中拥有cors软件包。

2 个答案:

答案 0 :(得分:1)

需要在您的Cloud Function中将以下内容添加到handle CORS requests

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

您可以尝试使用此示例。这是guthub repo的完整代码。

答案 1 :(得分:1)

可能与CORS不相关。检查Firebase功能日志以查看代码中是否有任何错误。

https://stackoverflow.com/a/51103084/5781575