我正在使用 Express.js 和 React 开发一个简单的应用程序,开发环境(本地计算机)中的两个应用程序都在不同的端口上,本地主机上的服务器(Express):3001 和本地主机上的前端(React): 3000。
我遇到的问题是,尝试使用 Fetch API Express 从前端发送数据不会收到 React 通过 POST 发送的数据。我做了一个从普通表单执行 POST 的测试,服务器确实接受了我通过 POST 发送的参数,所以我认为问题出在使用 Fetch API 从 Javascript 进行的调用上。
在 Express 中,我已经安装了 cors 模块来接受不同域的请求,但问题仍然存在。
为了更好地理解,下面是两者的代码片段。
...
// handler recieves the 'e' event object
formPreventDefault(e) {
var headers = new Headers();
headers.append('Accept', 'application/json, application/xml, text/plain, text/html, *.*');
headers.append('Content-Type', 'multipart/form-data; charset=utf-8');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Headers', 'Content-Type');
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
formData.append('email', 'demo@domain.com');
formData.append('password', '12345');
var options = {
headers: headers,
mode: 'no-cors', // crossdomain *
method: 'post',
body: JSON.stringify({ 'email': 'admin@domain.com', 'password': '12345' }) // formData
};
var request = new Request('http://localhost:3001/user/signin', options);
fetch(request).then(function(response) {
console.log("Success");
return response;
}).then(function(json) {
console.log(json);
}).catch(function(err) {
console.log("Error " + err);
})
// prevent submit form
e.preventDefault();
}
render() {
return (
<div className="row">
<div className="col-md-4 ">
<form id="myForm" action="http://localhost:3001/user/signin" method="post" onSubmit={this.formPreventDefault}>
<div className="form-group">
<label htmlFor ="email">Email address</label>
<input type="email" className="form-control" id="email" name="email" placeholder="Email" />
</div>
<div className="form-group">
<label htmlFor ="password">Password</label>
<input type="password" className="form-control" id="password" name="password" placeholder="*******" />
</div>
<button type="submit" className="btn btn-default">Submit</button>
</form>
</div>
</div>
);
}
}
...
快速 Controller
...
// Handle User Sign In on POST
exports.user_create_post = function(req, res) {
console.log(req.body); // This always returns an empty value
//Check that the name field is not empty
req.checkBody('email', 'Email address is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
//Run the validators
var errors = req.validationErrors();
//Create a genre object with escaped and trimmed data.
var user = new User(
{ email: req.body.email, password: req.body.password }
);
if (errors) {
//If there are errors render the form again, passing the previously entered values and errors
// res.render('users/sign_up', { title: 'Sign Up', user: user, errors: errors });
res.json({ user: user, errors: errors });
return;
}
else {
// Data from form is valid.
//Check if User with same email already exists if not the new user is saved
User.findOne({ 'email': req.body.email })
.exec( function(err, found_user) {
if (err) { return next(err); }
if (found_user) {
//User exists, redirect to the home page
// res.render('users/home', { title: 'Home', user: found_user });
res.json({ user: found_user });
}
else {
// Save user
user.save(function (err) {
if (err) { return next(err); }
// Create session
req.session.user_id = user._id.toString();
// User saved. Display user profile page
// res.render('users/home', { title: 'Home', user: user });
res.json({ user: user });
});
}
});
}
};
...
欢迎任何帮助
最佳答案
如果您的生产环境将同时托管前端和服务器,您的请求最终将不必处理 CORS。在这种情况下,我建议在您的前端 React Fetch 请求中定位端口 3000,并使用“代理”功能 Proxying API Requests in Development在您的前端服务器上进行开发。
基本上,把它放在你的 package.json 中
"proxy": "http://localhost:3001",
并将您的请求更改为:
var request = new Request('http://localhost:3000/user/signin', options);
编辑 清除此工作所需的获取请求:
fetch('http://localhost:3000/user/signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'email': 'admin@domain.com', 'password': '12345' }) // formData
}).then(function(response) {
...
关于javascript - Express 不使用 Fetch API 通过 POST 从 React 接收参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45305044/