【问题标题】:firebase cloud function CORS error with axios request带有axios请求的firebase云功能CORS错误
【发布时间】:2020-10-30 06:07:44
【问题描述】:

我有一个通用的云功能:

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 错误。

访问 XMLHttpRequest 在 'https://myurl/helloWorld' 来自 来源 'http://localhost:8080' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。 xhr.js?b50d:178 获取 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 包。

【问题讨论】:

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


    【解决方案1】:

    可能与 CORS 无关。检查 firebase 函数日志,看看您的代码中是否有任何错误。

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

    【讨论】:

      【解决方案2】:

      需要将以下内容添加到您的 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,完整代码在哪里。

      【讨论】:

      • 他们正在使用 CORS 中间件,应该可以解决这个问题。
      猜你喜欢
      • 2018-05-15
      • 1970-01-01
      • 2020-12-18
      • 2018-01-17
      • 2020-01-22
      • 2019-01-15
      • 2020-04-27
      • 1970-01-01
      • 2021-03-05
      相关资源
      最近更新 更多