Api request 在 swagger 和 postman 中有效,但在 js 中无效(使用 axios)

阿尔雷萨

我有这个 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

日期构造函数在IE中返回NaN,但在Firefox和Chrome中有效

HTTP DELETE在浏览器中有效,但在Postman或IOS App中无效

单一测试在PhantomJS中失败,但在Chrome和Firefox中有效

在TypeScript中创建GUID-函数在JS中有效,但在TS中无效

为什么我的API调用在chrome中有效,但在我的代码中无效?

HTTP POST请求在Postman中有效,但在代码中无效

.NET Core Web API中的IFormFile对于axios和ajax文件上载为空,但在Postman中有效

API端点链接在Postman中有效,但在带有ActiveResource的Ruby on Rails中无效

为什么此API请求在Postman中有效,但在Django测试中引发错误?

redash GET请求在POSTMAN上有效,但在axios上无效

mysql查询在phpmyadmin中有效,但在node.js中无效

从Vue.js应用程序(Axios)进行的2个同时API调用随机失败,但在Postman中工作

API调用在浏览器中有效,但在curl / wget中无效

添加的间距在Firefox中有效,但在Chrome和Safari中不起作用

垂直对齐文本和其他元素在页眉中有效,但在页脚中无效

$ _POST和javascript –在javascript中有效,但在jquery插件中无效

日期差异在Firefox和IE中有效,但在Chrome中返回NaN

为什么线性混合模型在SAS和nlme中有效但在lme4中无效?

AJAX在jQuery中有效,但在香草JS中无效

该示例在js小提琴中有效,但在自制页面中无效

React Native + fetch + API:DELETE 请求在 App 中失败,在 Postman 中有效

POST/PATCH 在 LoopBack Explorer 中有效,但在 Postman 中无效

为什么相同的 POST 请求在 POSTMAN 中有效,但在浏览器 AJAX 中无效(404 Not Found)?

JS 和 Bootstrap 在 Codepen 中有效,但在本地打开时无效

Webservice 在 Android Retrofit 2 中给出错误 401,但在 Volley 和 Postman 中有效

Http 请求在 PostMan 中有效,但在 JS 中无效

Postman 和 RestTemplate 的 API 调用中的主体参数相同,但只有 Postman 有效

GET 请求通过 Axios 返回错误 404,但在 Postman 中有效?

fish shell:为什么`file`which command`在zsh和bash中有效,但在fish中无效?