Ill*_*lep 0 node.js firebase reactjs
运行我的项目时出现以下错误。
无法加载 https://us-centralx-xxx.cloudfunctions.net/xxx:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:3000 '。响应的 HTTP 状态代码为 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'
};
Run Code Online (Sandbox Code Playgroud)
但是,错误仍然存在。我该如何解决这个问题?
更新
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
});
});
Run Code Online (Sandbox Code Playgroud)
在您的 Node.js 服务器中设置适当的标头以允许受控 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();
});
Run Code Online (Sandbox Code Playgroud)
您的另一个选择是使用Express.js CORS 包并根据您的需要对其进行配置。
| 归档时间: |
|
| 查看次数: |
6025 次 |
| 最近记录: |