我使用axios通过id更新文档,但是我的[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
将不正确的数据发送到后端。
这是一条快速路线:
POST request
这是处理表单和请求的React组件的一部分(我没有显示所有代码,因为其他部分可以工作。如有必要,我将显示所有代码):
router.post('/', async (req, res) => {
try {
const updatedPost = await Data.updateOne(
{ _id: "5d28a6fcec97b111c2f5867d" },
{
$set: {
phone: req.body.phone,
email: req.body.email,
title: req.body.title,
longTitle: req.body.longTitle,
introTitle: req.body.introTitle,
introLongTitle: req.body.introLongTitle,
videoLink: req.body.videoLink,
introText: req.body.introText
}
}
);
res.json(updatedPost);
}
catch (err) {
res.json({ message: err });
}
});
当我在输入中键入一些文本并提交表单时, const data = {
"phone": this.state.phone ? this.state.phone : this.state.data[0].phone,
email: this.state.email ? this.state.email : this.state.data[0].email,
title: this.state.title ? this.state.title : this.state.data[0].title,
longTitle: this.state.longTitle ? this.state.longTitle : this.state.data[0].longTitle,
introTitle: this.state.introTitle ? this.state.introTitle : this.state.data[0].introTitle,
introLongTitle: this.state.introLongTitle ? this.state.introLongTitle : this.state.data[0].introLongTitle,
videoLink: this.state.videoLink ? this.state.videoLink : this.state.data[0].videoLink,
introText: this.state.introText ? this.state.introText : this.state.data[0].introText
};
axios.post('http://localhost:5555/data', {data})
.then(res => {
console.log(data);
})
显示具有相同对象的对象。但是用console.log
检查数据后,它在GET request
中显示了NULL
字段。我尝试在axios请求中使用JSON
,但这没有帮助。
也许有人知道,什么是不正确的。
感谢您的帮助!)
答案 0 :(得分:0)
将您的Axios请求更改为:
axios.post('http://localhost:5555/data', data)
.then(res => console.log(data));
您使用对象简写会在您的数据对象中创建一个附加级别:
// If you do
axios.post('http://localhost:5555/data', {data})
// Express will receive it as
req.body = {
data: {
phone: ...,
email: ...,
...
}
}
此外,如果Express托管了您的客户端和API,则可以将Axios请求更改为:
axios.post('/data', data)
.then(res => {
console.log(res.data)
// Do stuff with updated post here
})