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正确获取页面载荷标签解析结果:

相关推荐
椰羊~王小美9 分钟前
除了前端 JS 配置的国际化,对于 JS 没覆盖到的文本,怎么实现国际化
前端·javascript·状态模式
A_aspectJ16 分钟前
【Java基础开发】基于 Java Swing +MySQL + JDBC 版实现图书管理系统
java·开发语言·mysql
TE-茶叶蛋16 分钟前
Spring最核心扩展点:BeanPostProcessor
java·后端·spring
Mr.456717 分钟前
SpringBoot多模块依赖冲突排查与架构优化实战(避坑指南)
java·spring boot·架构
AC赳赳老秦17 分钟前
DBA 专属方案:用 OpenClaw 实现 SQL 语句优化、慢查询分析、数据库备份巡检全自动化
服务器·前端·数据库·ffmpeg·自动化·deepseek·openclaw
学术阿凡提18 分钟前
Spring Boot 优雅实现异步调用:从入门到自定义线程池与异常处理
java·数据库·算法
我是无敌小恐龙33 分钟前
Java SE 零基础入门Day06 方法重载+Debug调试+String字符串全套API详解(超全干货)
java·开发语言·人工智能·python·transformer·无人机·量子计算
燐妤34 分钟前
前端HTML编程1:初识html
前端·html5
xiaoye370835 分钟前
java接口文档工具 swagger2和swagger3对比
java·服务器·前端
三维频道36 分钟前
工业级三维扫描实测:汽车灯具复杂结构件的全尺寸 3D 测量方案分析
java·人工智能·python·数码相机·3d·汽车·汽车轻量化制造