我有这个 POST api 招摇:在此处输入图像描述 在此处
输入图像描述
当我大摇大摆地发送请求时,它返回 200 状态码
我也在邮递员中尝试了完全相同的请求,它还返回 200 状态码,所以一切都很好:在此处输入图像描述
但是对于 js,我在 js 中发送完全相同的请求,但服务器返回 400 状态代码和消息:"title can not be empty"
但我确定我正确发送了标题。
这是我的代码:
export const createFood = async (title, description, file, price) => {
try {
const { data } = await client.post(`/Restaurant/food`, {
title,
description,
"file.form_file": file,
price: parseFloat(price),
});
return data;
} catch (error) {
return error.response.data;
}
};
这是浏览器网络日志:在此处输入图像描述 在
此处
输入图像描述
我究竟做错了什么?
在 js 中,您将数据作为对象发送。但您应该将其作为表单数据发送,如下所示:
export const createFood = async (title, description, file, price) => {
const formData = new FormData();
formData.append("title", title);
formData.append("description", description);
formData.append("file.form_file", file);
formData.append("price", parseFloat(price));
try {
const { data } = await client.post(`/Restaurant/food`, formData);
return data;
} catch (error) {
return error.response.data;
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句