【问题标题】:CORS not working on specific domains in firebase cloud functionsCORS 不适用于 Firebase 云功能中的特定域
【发布时间】:2021-03-21 14:49:28
【问题描述】:
const whitelist = ["http://mywebsite.com", "http://localhost:5000"]

const corsOptions = {
    origin: function (origin, callback) {
      if (whitelist.indexOf(origin) !== -1) {
        callback(null, true)
      } else {
        callback(new Error('Not allowed by CORS'))
      }
    }
  }

const cors = require('cors')(corsOptions);

exports.getUserProfile = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        try {
            //... here we fetch the user profile and send it in response
        } catch (err) {
            res.json({
                status: "error",
                message: err
            })
        }
    });
});

我以这种方式使用 CORS,所以我只能让我自己的网站和 localhost:5000 向我正在使用的云功能发出请求。 localhost:5000 适合我,所以我可以在部署文件之前在本地测试东西。

  1. 从 reqbin.com 向我的云功能发出请求有效,为什么?它不应该不起作用吗,因为我已将域指定为来自 mywebsite.com 或 localhost:5000?
  2. 是否有任何其他方法可以在本地测试内容而不必将 localhost:5000 包含在白名单中?我正在使用firebase serve 进行测试,但我假设这不起作用,因为来自 mywebsite.com 的请求不会被处理

【问题讨论】:

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


    【解决方案1】:

    这将通过直接使用 cors 库中的源来帮助您。

    const cors = require('cors')
    
    const corsHandler = cors({
        origin:["http://mywebsite.com", "http://localhost:5000"]
    });
    
    exports.getUserProfile = functions.https.onRequest((req, res) => {
        corsHandler(req, res, async () => {
            try {
                //... here we fetch the user profile and send it in response
            } catch (err) {
                res.json({
                    status: "error",
                    message: err
                })
            }
        });
    });
    

    【讨论】:

    • 这个根本不行,连我自己网站的请求都不起作用,控制台老是抛出Access to XMLHttpRequest at 'https://users.mywebsite.com/api/getUserFavorites' from origin 'https://www.mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.错误,我还在白名单里加了https我网站的版本.
    • 您必须提供此列表中的所有子域和域。
    • 我将 corsHandler 更改为 const corsHandler = cors({origin:["https://mywebsite.com","http://mywebsite.com","https://www.mywebsite.com","http://www.mywebsite.com","https://users.mywebsite.com","http://users.mywebsite.com","http://localhost:5000"]}); 并且这有效,但当我从 reqbin.com 发出请求时它也有效。 :( 回到第一格...
    • 我无法想象为什么会发生这种情况,您可以尝试在后端记录来源吗?也许它会以某种方式更改为接受的之一?
    • @EmilGi 我不知道这是怎么回事,但是当我再次尝试时,这才起作用。不知道发生了什么,我重新部署了整个 firebase 应用程序并且它工作了(我只部署了 firebase deploy --only functions 的功能。叹气。非常感谢您的帮助。
    猜你喜欢
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2018-08-27
    • 2021-04-08
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多