所以当我尝试使用 React 将数据发送到后端时,我遇到了这个错误。据我所知,我需要允许在后端和.htaccess
文件中进行通信。以下是我使用的一些链接:
没有 'Access-Control-Allow-Origin' - 节点/Apache 端口问题
Access-Control-Allow-Origin 标头如何工作?
他们都有代码,但没有帮助。
到目前为止,我的服务器端代码是这样的:
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
文件,但我都是在本地完成的,所以我不确定我是否可以使用它。
在我看来,我允许我所需要的一切,但我想这还不够。
如果您要标记为重复,请至少确保我的问题包含在答案中。