【发布时间】:2018-11-30 18:19:43
【问题描述】:
所以当我尝试使用 React 将数据发送到后端时,我遇到了这个错误。据我所知,我需要允许后端和.htaccess 文件中的通信。以下是我使用的一些链接:
No 'Access-Control-Allow-Origin' - Node / Apache Port Issue
How does Access-Control-Allow-Origin header work?
他们都有代码,但没有帮助。
到目前为止,我的服务器端代码是这样的:
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 文件,但我都是在本地完成的,所以我不确定我是否可以使用它。
在我看来,我允许所有我需要的,但我想这还不够。
如果您要标记为重复,请至少确保答案涵盖了我的问题。
【问题讨论】:
标签: javascript node.js reactjs cors