运行项目时出现以下错误。
Failed to load https://us-centralx-xxx.cloudfunctions.net/xxx: 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.
阅读了很多SO帖子后,我找到了以下解决方案,我需要添加 Access-Control-Allow-Origin
、 Access-Control-Allow-Methods
和 Access-Control-Allow-Headers
const HEADERS = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:3000/',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'X-Requested-With,content-type'
};
但是,错误仍然存在。我该如何解决这个问题?
更新
exports.uploadFile = functions.https.onRequest((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.status(200).json({
message: req.body
});
});
最佳答案
在 Node.js 服务器中设置适当的 header 以允许受控的 CORS 请求:
app.use((req, res, next) => {
const origin = req.headers.origin;
// arrayOfValidOrigins is an array of all the URL from where you want to allow
// to accept requests. In your case: ['http://localhost:3000'].
// In case you want to accept requests from everywhere, set:
// res.setHeader('Access-Control-Allow-Origin', '*');
if (arrayOfValidOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
// Here allow all the HTTP methods you want
res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
// Here you allow the headers for the HTTP requests to your server
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
// Method to reference to the next Node.js function in your flow
next();
});
您的另一个选择是使用 Express.js CORS package并根据您的需要进行配置。
关于node.js - 在本地主机上运行时,Firebase 出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204368/