gpt4 book ai didi

javascript - Firebase HTTP 函数 CORS 问题

转载 作者:行者123 更新时间:2023-12-02 17:27:49 26 4
gpt4 key购买 nike

从客户端调用 Firebase http 函数时,我无法使其正常工作。以下是客户端上的错误:

OPTIONS https://us-central1-my-app.cloudfunctions.net/my-func 500 ()

Failed to load https://us-central1-my-app.cloudfunctions.net/my-func:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
The response had HTTP status code 500.

这是我的函数的样子:

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

exports.func = functions.https.onRequest((req, res) => {
return cors((req, res, () => {
res.send("hello");
}));
});

Firebase 功能日志提供以下信息:

TypeError: Cannot read property 'origin' of undefined
at /user_code/node_modules/cors/lib/index.js:219:39
at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
at exports.pay.functions.https.onRequest (/user_code/my-func.js:11:10)

请注意,调用堆栈中的 11:10 是这样的:return cors((req, res, () => {

我发出的请求是在请求正文中发送一个带有单个键:值对的对象。我根据我在 SO 上看到的其他问题添加了 cors 中间件,但没有运气!

编辑:添加请求代码:

function post(url, obj) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/json");

req.onload = function() {
if(req.status == 200) {
return resolve(req.response);
}
else {
return reject(Error(req.statusText));
}
};

req.onerror = function() {
return reject(Error("Network Error"));
};

req.send(JSON.stringify(obj));
});
}

最佳答案

程序员错误,像往常一样:

cors((req, res, () => {
res.send("hello");
}));

应该是:

cors(req, res, () => {
res.send("hello");
});

cors 参数周围有一组额外的括号。

关于javascript - Firebase HTTP 函数 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com