【发布时间】:2022-02-06 06:32:24
【问题描述】:
疯狂地抓挠我的头,我的“POST”路线工作得很好,我的“PUT”路线的完全相同的代码在浏览器中返回"SyntaxError: Unexpected end of JSON input"。它会更新,但不会通过我的 fetch 请求的 .then() 部分,而是直接进入 catch 块。
在我的 react 应用上获取:
const updateCourse = async(e) => {
e.preventDefault();
const encodedCreds = btoa(
`${props.creds.emailAddress}:${props.creds.password}`
);
await fetch('http://localhost:5000/api/courses/' + params.id, {
method: 'PUT',
headers : {
'Content-Type': 'application/json',
Authorization: `Basic ${encodedCreds}`,
},
body: JSON.stringify(course)
}).then(res => res.json())
.then((data) => {
if(data.message) {
setErrorMessage(data.message.errors)
}else{
nav('/course/' + data)
}
})
.catch((err) => {
console.log('error message', err)
});
快速 API 响应:
router.put("/api/courses/:id", authUser, async (req, res) => {
try {
const findCourse = await courses.findOne({
where: {
id: req.params.id,
},
});
if (findCourse) {
//----IF ITS A VALID COURSE--//
const updateCourse = await findCourse.update(req.body);
res.status(204);
res.json(updateCourse.id)
} else {
res.json({
message: "Could not find course",
});
}
} catch (err) {
res.json({
message: err
});
}
});
【问题讨论】:
标签: reactjs express sequelize.js