Api 请求在 swagger 和 postman 中有效,但在 js 中无效(使用 axios)
Api request Works in swagger and postman but doesn't work in js (using axios)
我有这个 POST api 招摇过市:
enter image description here
enter image description here
当我大摇大摆地发送请求时 returns 200 状态码
我也在邮递员中尝试了完全相同的请求,它也是 returns 200 状态码所以一切都很好:
enter image description here
但是当涉及到 js 时,我在 js 中发送了完全相同的请求,但是服务器 returns 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;
}
};
这是浏览器网络日志:
enter image description here
enter image description here
我做错了什么?
在 js 中,您将数据作为对象发送。但你应该像这样 form-data 发送它:
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;
}
};
我有这个 POST api 招摇过市:
enter image description here
enter image description here
当我大摇大摆地发送请求时 returns 200 状态码
我也在邮递员中尝试了完全相同的请求,它也是 returns 200 状态码所以一切都很好: enter image description here
但是当涉及到 js 时,我在 js 中发送了完全相同的请求,但是服务器 returns 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;
}
};
这是浏览器网络日志:
enter image description here
enter image description here
我做错了什么?
在 js 中,您将数据作为对象发送。但你应该像这样 form-data 发送它:
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;
}
};