vue项目调用netcore webapi接口提示:400 Bad Request的解决

后端接口地址:

/api/Menu/GetMenuPageList

后端接口既有requestParams参数,也有requestBody参数

cs 复制代码
 [HttpPost]
 [Route("GetMenuPageList")]
 public JsonResult GetMenuPageList(MenuDTO request, int pageIndex, int pageSize)

使用post请求,这里request不需要使用 [FromBody] 标签

原来的获取菜单列表语句是如此写的:

TypeScript 复制代码
return http
      .request<MenuProps[], Response<MenuProps[]>>(Api.getMenuPageList, 'POST',{"pageIndex":1,"pageSize":10},{'data':{"parentId": 1,"name":""}})

出现了400 bad request错误

打开chrome的网络标签,在webapi预览项中发现如下错误:

The request field is required.

网上搜索,多次尝试,终于找到适合的方法

新的webapi接口获取菜单列表语句:

TypeScript 复制代码
 return http.request<MenuProps[], Response<MenuProps[]>>(Api.getMenuPageList+'?pageIndex=1&pageSize=10',"post_json",{'parentId': 0, 'name': ''} )
 .then((res) => {

此处request方法中method参数必须使用post_json形式,如果使用post。也会报 400错误,bad request

这里的post_json是程序自定义的method类型。具体所作的处理如下:

post形式,根据方法类型调用了axios的post方法:

TypeScript 复制代码
case 'POST':
          return _axios.post(url, toUrlencoded(params), config);

function toUrlencoded(params?: Record<string | number, any>) {
  const urlencoded = new URLSearchParams();
  for (const key in params) {
    if (params[key] !== undefined) {
      urlencoded.append(key, params[key]);
    }
  }
  return urlencoded;
}

这里可见,对传递进来的requestbody对象:{'parentId': 0, 'name': ''},做了编码处理

而post_json形式调用所调用的axios的post方法为:

TypeScript 复制代码
case 'POST_JSON':
          return _axios.post(url, params, config);

对传递的 requestbody对象:{'parentId': 0, 'name': ''}未做任何处理。因为 {'parentId': 0, 'name': ''}此对象本身就是json格式,不进行任何处理就能够使用。反而使用toUrlencoded进行处理后却会造成问题,不再是标准的json对象了。

400错误时候载荷标签的参数解析结果:

200正确获取页面载荷标签解析结果:

相关推荐
天天扭码1 小时前
零基础 | 入门前端必备技巧——使用 DOM 操作插入 HTML 元素
前端·javascript·dom
Hanson Huang1 小时前
【数据结构】堆排序详细图解
java·数据结构·排序算法·堆排序
路在脚下@2 小时前
Redis实现分布式定时任务
java·redis
xrkhy2 小时前
idea的快捷键使用以及相关设置
java·ide·intellij-idea
巨龙之路2 小时前
Lua中的元表
java·开发语言·lua
咖啡虫2 小时前
css中的3d使用:深入理解 CSS Perspective 与 Transform-Style
前端·css·3d
拉不动的猪2 小时前
设计模式之------策略模式
前端·javascript·面试
旭久2 小时前
react+Tesseract.js实现前端拍照获取/选择文件等文字识别OCR
前端·javascript·react.js
独行soc2 小时前
2025年常见渗透测试面试题-红队面试宝典下(题目+回答)
linux·运维·服务器·前端·面试·职场和发展·csrf
花花鱼2 小时前
itext7 html2pdf 将html文本转为pdf
java·pdf