NodeJS firebase云函数CORS错误与axios请求

jjhzyzn0  于 2023-04-05  发布在  Node.js
关注(0)|答案(2)|浏览(133)

我有一个通用的云函数:

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

我有两个问题:
1.我收到CORS错误。
CORS策略已阻止从源“http://localhost:8080”访问位于“https://myurl/helloWorld”的XMLHttpRequest:No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js?b50d:178 GET https://us-central1-dev-imcla.cloudfunctions.net/helloWorld net::ERR_FAILED
1.如果我从浏览器打开cors插件,或者从postman调用函数,我会得到这个错误:
错误:您的客户端没有权限访问该页面,请点击这里登录
错误:请求失败,状态代码403 at createError(createError.js?2d 83:16)at settle(settle.js?467 f:17)at XMLHttpRequest.handleLoad(xhr.js?b50 d:61)
问题是,我既是经过身份验证的用户,又在云代码中有cors包。

njthzxwz

njthzxwz1#

可能与CORS无关。检查firebase函数日志,查看代码中是否有任何错误。
https://stackoverflow.com/a/51103084/5781575

xt0899hw

xt0899hw2#

需要添加以下内容以在Cloud Function中处理CORS请求:

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,其中是完整的代码。

相关问题