【发布时间】:2019-05-02 13:16:01
【问题描述】:
我正在本地主机上构建 Web 应用程序。
前端是Reactjs框架,运行在localhost:3000
后端是nodejs + Express,运行在localhost:4000
现在,我创建了下面的 API:
router.post('/register', function (req, res) {
console.log(req.body); // {}, why it is empty?
// create new instance, save it to database
User.create(req.body).then(function () {
res.send('success');
});
});
前端部分是:
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values); // value is not empty, I have tested! So we did send something to the API
const input = JSON.stringify({
username: values.username,
password: values.password,
});
console.log(input);
$.ajax({
url: `${API_ROOT}/register`,
method: 'POST',
data: JSON.stringify({
username: values.username,
password: values.password,
}),
}).then((response) => {
if (response === 'success') {
this.props.history.push('/login');
} else {
console.log('do not jump');
}
});
}
});
}
我已经通过邮递员测试了API,我可以将用户添加到MongoDB,所以API很好。
我有我发送给 API 的 console.log,它不是空的,但是,后端 API 接收到空的请求正文。我已经修复了“Access-Control-Allow-Origin”问题,所以我想我确实向 API 发送了一些东西,但是后端 API 收到了空的请求正文。
【问题讨论】:
-
也许您必须在请求中添加内容类型?
headers: { 'Content-Type': 'application/json' } -
你试过添加bodyparser中间件
router.use(bodyParser.json())吗? -
@Tholle 你说的太对了!添加表头后,问题解决,谢谢!!!
-
我的回答对你有用吗?如果是这种情况,请考虑 accepting it。