使用React和Express阻止跨域请求 [英] Cross-Origin Request Blocked with React and Express
问题描述
因此,当我尝试使用React将数据发送到后端时,我遇到了此错误。据我了解,我需要允许后端和 .htaccess
文件中的通信。这是我使用的一些链接:
So I hit this error, when I was trying to send data to the back end using React. From what I learnt I need to allow the communication on the back-end and in the .htaccess
file. Here are some of the links I used:
Access-Control-Allow-Origin标头如何工作?
他们两个都有代码,但这没有帮助。
Both of them have code, but it didn't help.
到目前为止,我的服务器端代码是这样的:
So far my Server-side code is this:
app.use(function (req, res, next) {
// Website you wish to allow to connect
// res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'POST');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
这是我的客户端代码:
sendMail(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var contactReason = document.getElementById('contactReason').value;
var email = document.getElementById('email').value;
var additionalInfo = document.getElementById('additionalInfo').value;
var body = {
name: name,
contactReason: contactReason,
email: email,
additionalInfo: additionalInfo,
};
console.log(JSON.stringify(body));
fetch('http://localhost:4000/', {
method: 'POST',
body: body,
}).then(r => console.log(r)).catch(e => console.log(e));
}
那么我想念什么?我没有 .htaccess
文件,但是我在本地完成所有操作,因此不确定是否可以使用它。
So what am I missing? I do not have an .htaccess
file, but I'm doing it all locally so I'm not sure if I can even use it.
在我看来,我同意了我所需要的一切,但我想这还不够。
It looks to me like I'm allowing all I need, but I guess it's not enough.
如果您要标记作为重复项,请至少确保答案涵盖了我的问题。
If you're going to mark as a duplicate, please at least make sure my issues are covered by the answer.
推荐答案
有一个名为cors的节点包,它使
There's a node package called cors which makes it very easy.
$ npm install cors
const cors = require('cors')
app.use(cors())
您不需要任何配置即可允许全部操作。
You don't need any config to allow all.
有关更多信息,请参见Github存储库: https://github.com/expressjs/cors
See the Github repo for more info: https://github.com/expressjs/cors
这篇关于使用React和Express阻止跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!