无法从 POST 到 api,使用 fetch 时出现错误 400
can't do POST to api, error 400 using fetch
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);
})
this.state.user 基本上是一个类似 {user: {name:"someone"}
的对象,我的服务器端代码只是这样做
router.post('/signup', (req, res, next) => {
console.log(req.body) // empty object
}
我认为 fetch
有问题,在网络选项卡中没有看到任何数据被传递。
在 body
处设置之前将 this.state.user
传递到 JSON.stringify()
或使用 FormData
到 POST
键值对。 body
不期望 javascript
对象。
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
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);
})
this.state.user 基本上是一个类似 {user: {name:"someone"}
的对象,我的服务器端代码只是这样做
router.post('/signup', (req, res, next) => {
console.log(req.body) // empty object
}
我认为 fetch
有问题,在网络选项卡中没有看到任何数据被传递。
在 body
处设置之前将 this.state.user
传递到 JSON.stringify()
或使用 FormData
到 POST
键值对。 body
不期望 javascript
对象。
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