从客户端调用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));
});
}
答案 0 :(得分:4)
程序员错误,像往常一样:
cors((req, res, () => {
res.send("hello");
}));
应该是:
cors(req, res, () => {
res.send("hello");
});
在cors
args附近有一套额外的parens。