Javascript 无法发布到api,使用fetch时出现错误400
基本上,this.state.user是一个类似{user:{name:someone}的对象,我的服务器端代码就是这样做的Javascript 无法发布到api,使用fetch时出现错误400,javascript,ajax,reactjs,fetch,Javascript,Ajax,Reactjs,Fetch,基本上,this.state.user是一个类似{user:{name:someone}的对象,我的服务器端代码就是这样做的 fetch('/auth/signup', { method: 'POST', body: this.state.user, headers: { 'Content-Type': 'application/json' }, }) .then(function(response) {
fetch('/auth/signup', {
method: 'POST',
body: this.state.user,
headers: {
'Content-Type': 'application/json'
},
})
.then(function(response) {
return response.json();
})
.then(data => {
console.log(data);
})
我认为fetch有问题,在网络选项卡中没有看到任何数据被传递。在设置body之前将this.state.user传递到JSON.stringify,或者使用FormData发布键、值对。body不需要javascript对象
您在[console]窗口中看到某条消息了吗?@eeya 400错误,错误请求在[fetch]方法上,当您将url替换为“signup”而不是“auth/signup”时会发生什么情况?@eeya现在我设法传递数据,但服务器返回req.body为{}hmmm。。。
router.post('/signup', (req, res, next) => {
console.log(req.body) // empty object
}
body: JSON.stringify(this.state.user)
let fd = new FormData();
let {user} = this.state.user;
for (let prop in user) {
fd.append(prop, JSON.stringify(user[prop]));
}
body: fd