除了创建我的项目版本外,我正在尝试在Udemy上遵循代码。使用bcrypt和jwt后,我无法在我的应用中发布任何帖子。我可以正常登录,但是尝试发布内容时出现422错误。
这就是让我陷入困境的原因。
const twottSubmitHandler = async (event) => {
event.preventDefault();
try {
const formData = new FormData();
formData.append("title", formState.inputs.title.value);
formData.append("description", formState.inputs.description.value);
formData.append("creator", auth.userId);
await sendRequest("http://localhost:3001/api/twotts", "POST", formData, {
Authorization: "Bearer " + auth.token,
});
history.push("/");
} catch (err) {}
};
在twotts控制器中,这就是引发错误的原因,
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(new HttpError("Invalid input passed", 422));
}
const { title, description, creator } = req.body;
const createdTwott = new Twott({
title,
description,
creator,
});
有没有一种方法可以使它使用JSON.stringify而不是FormData进行添加?使用
try {
await sendRequest(
"http://localhost:3001/api/twotts",
"POST",
JSON.stringify({
title: formState.inputs.title.value,
description: formState.inputs.description.value,
creator: auth.userId,
}),
{ Authorization: "Bearer " + auth.token },
{ "Content-Type": "application/json" }
);
history.push("/");
} catch (err) {}
我仍然收到无效的输入。如果我将Authorization参数放在其他任何地方,都会遇到身份验证问题。
回购的链接是https://github.com/preintercede/Twotter(带有提交),以防我错过了一部分。
答案 0 :(得分:2)
您正在构造FormData
并与Content-Type: multipart/form-data
(隐式)发送。 express-validator
不能立即验证此类数据(原因:https://github.com/express-validator/express-validator/issues/276)
一种解决方案是使用https://github.com/expressjs/multer,但我的建议是使用正确的Content-Type
提交JSON数据,就像您已经在处理其他请求一样:
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
modified: src/twotts/pages/NewTwott.js
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
@ src/twotts/pages/NewTwott.js:39 @ const NewTwott = () => {
event.preventDefault();
try {
- const formData = new FormData();
- formData.append("title", formState.inputs.title.value);
- formData.append("description", formState.inputs.description.value);
- formData.append("creator", auth.userId);
- await sendRequest("http://localhost:3001/api/twotts", "POST", formData, {
+ await sendRequest("http://localhost:3001/api/twotts", "POST", JSON.stringify({
+ title: formState.inputs.title.value,
+ description: formState.inputs.description.value,
+ creator: auth.userId
+ }), {
Authorization: "Bearer " + auth.token,
+ "Content-Type": "application/json",
});
history.push("/");
} catch (err) {}
我建议将其包装到一个辅助函数中。这也可以将Bearer令牌设置为请求标头(如果存在)。