解决axios发送post请求,springMVC接收不到数据问题

ops/2024/9/24 22:23:56/

今天发现一个问题:

vue组件中无法正确接收并处理axios请求

这个问题已经困扰我好久了,在电脑面前坐了两天只能确定前端应该是正确的发送了请求,但发送请求后无法正确接受后端返回的数据。

问题:vue组件无法接受后端数据

错误代码如下:

javascript">axios.post("/simple_query",{
},this.simple_query_input).then(res=>{    console.log(res);
}).catch(err=>{console.log(err);
})
java">@RequestMapping(value = "/simple_query",method = RequestMethod.POST)
public cheName handleSimpleQuery(@RequestParam("simple_query_input") String simpleQueryInput) throws Exception {}

网上找到也有类似未解决的:

Spring MVC的Controller里面使用了@RequestParam注解来接收参数,但是只在GET请求的时候才能正常访问,在使用POST请求的时候会产生找不到参数的异常。原本好好的POST请求开始报400错误,找不到REST服务,一般情况下报这种错误多是由于POST请求时传递的参数不一致,但是这次不存在这种问题,百思不得其解啊。。。

还有这个:axios发送post请求,springMVC接收不到数据问题

java">@RequestMapping(method = RequestMethod.POST, value = "/test")
@ResponseBody
public ResponseEntity testDelete(@RequestParam("id") Integer id)throws Exception {return ResponseEntity.ok();
}

代码中是规定了请求方式POST,使用@RequestParam接收id参数。

然后前台请求参数也对,是这个形式的{id:111},看起来没错啊,参数名完全一样,但是后台报错Required String parameter 'id' is not present,说id参数必须传过来。分析问题
虽然前端传递的参数形式为{id: 111},看起来id的参数名确实是一样的,但是这个参数是作为请求的body而非作为普通参数或query parameter传递的。因此无法直接使用@RequestParam注释接收它。

今天就俩解决一下吧:

SpringMVC@PathVariable@RequestBody、@RequestParam的使用场景以及对应的前端axios写法是什么呢?

一、@PathVariable

axios代码:

javascript">axios.post('http://localhost:8080/endpoint3/' + this.firstName + '/' + this.lastName)
.then(response => {console.log(response.data);
})
.catch(error => {console.error(error);
});	

SpringMvc的controller代码:

java">@PostMapping("/endpoint3/{firstName}/{lastName}")
@ResponseBody
public String endpoint2(@PathVariable("firstName") String firstName,  @PathVariable("lastName") String lastName) {// 处理请求逻辑return "Hello, " + firstName + " " + lastName;
}

二、@RequestBody

axios代码:

javascript">axios.post('http://localhost:8080/endpoint2', {firstName: this.firstName, lastName: this.lastName})
.then(response => {console.log(response.data);
})
.catch(error => {console.error(error);
});	

SpringMvc的controller代码:

java">@PostMapping("/endpoint2")
@ResponseBody
public String endpoint2(@RequestBody Map<String, Object> requestBody) {String firstName = Objects.toString(requestBody.get("firstName"));String lastName = Objects.toString(requestBody.get("lastName"));// 处理请求逻辑return "Hello, " + firstName + " " + lastName;
}

三、@RequestParam

axios代码:

javascript">const formData = new FormData();
formData.append('firstName', this.firstName);
formData.append('lastName', this.lastName);
axios.post('http://localhost:8080/endpoint1', formData)
.then(response => {console.log(response.data);
})
.catch(error => {console.error(error);
});	

SpringMvc的controller代码:

java">@PostMapping("/endpoint1")
public String handlePostRequest(@RequestParam("firstName") String firstName,@RequestParam("lastName") String lastName) {// 处理请求逻辑return "Hello, " + firstName + " " + lastName;
}

前台完整代码:

<!DOCTYPE html>
<html>
<head><script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.min.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/axios/1.6.8/axios.min.js"></script>
</head>
<body><div id="app"></div><script>new Vue({el: '#app',data () {return {firstName: "John",lastName: "Doe"}},mounted () {const formData = new FormData();formData.append('firstName', this.firstName);formData.append('lastName', this.lastName);axios.post('http://localhost:8080/endpoint1', formData).then(response => {console.log(response.data);}).catch(error => {console.error(error);});	axios.post('http://localhost:8080/endpoint2', {firstName: this.firstName, lastName: this.lastName}).then(response => {console.log(response.data);}).catch(error => {console.error(error);});	axios.post('http://localhost:8080/endpoint3/' + this.firstName + '/' + this.lastName).then(response => {console.log(response.data);}).catch(error => {console.error(error);});	}})</script></body>

后台核心代码:

java">@RestController
@CrossOrigin
public class MySpringMvcController {@PostMapping("/endpoint1")public String handlePostRequest(@RequestParam("firstName") String firstName,@RequestParam("lastName") String lastName) {// 处理请求逻辑return "Hello, " + firstName + " " + lastName;}@PostMapping("/endpoint2")@ResponseBodypublic String endpoint2(@RequestBody Map<String, Object> requestBody) {String firstName = Objects.toString(requestBody.get("firstName"));String lastName = Objects.toString(requestBody.get("lastName"));// 处理请求逻辑return "Hello, " + firstName + " " + lastName;}@PostMapping("/endpoint3/{firstName}/{lastName}")@ResponseBodypublic String endpoint2(@PathVariable("firstName") String firstName,  @PathVariable("lastName") String lastName) {// 处理请求逻辑return "Hello, " + firstName + " " + lastName;}}

  问题来源:

vue组件中无法正确接收并处理axios请求_前端-CSDN问答


http://www.ppmy.cn/ops/41995.html

相关文章

什么是直接内存(NIO)

直接内存不受 JVM 内存回收管理&#xff0c;是虚拟机的系统内存&#xff0c;常见于 NIO 操作时&#xff0c;用于数据 缓冲区&#xff0c;分配回收成本较高&#xff0c;但读写性能高&#xff0c;不受 JVM 内存回收管理。 举例 当上传一个较大文件&#xff08;200M&#xff09;…

服务器docker启动

一、写sh文件 写一个sh文件&#xff0c;方便后续启动 docker stop nacos docker stop rabbitmq docker stop redis docker stop xxl-job-admin docker stop mysql docker stop gogs docker stop elasticsearch docker stop kibanadocker start nacos docker start rabbitmq d…

android 界面布局中图片按键的实现

在Android界面布局中实现图片按键,通常可以通过ImageButton或者ImageView结合OnClickListener来完成。下面分别介绍这两种方法: 1. 使用ImageButton ImageButton是Android提供的一个控件,它继承自ImageView,因此可以显示图片,并且具备按钮的功能,即可以监听点击事件。 …

大语言模型量化方法对比:GPTQ、GGUF、AWQ

GPTQ: Post-Training Quantization for GPT Models GPTQ是一种4位量化的训练后量化(PTQ)方法&#xff0c;主要关注GPU推理和性能。 该方法背后的思想是&#xff0c;尝试通过最小化该权重的均方误差将所有权重压缩到4位。在推理过程中&#xff0c;它将动态地将其权重去量化为f…

C++基础与函数解析 | 函数的声明与定义 | 函数调用 | 函数详解 | 函数重载 | 重载解析 | 递归函数 | 内联函数 | 函数指针

文章目录 一、函数基础1.基本函数定义2.函数的声明与定义3.函数调用 二、函数详解1.参数2.函数体3.返回类型 三、函数重载与重载解析1.函数重载2.重载解析 四、函数相关的其他内容1.递归函数2.内联函数3.constexpr函数&#xff08;C11起&#xff09;4.consteval 函数 (C20 起 )…

[AI]-(第1期):OpenAI-API调用

文章目录 一、OpenAI API中使用GPT-3.5-turbo模型充值方式使用模型计费方式价格说明相关限制和条款 二、接入一个OpenAI API流程1. 获取OpenAI API 密钥2. 集成ChatGPT到小程序3. 处理用户输入4. 调用OpenAI API5. 返回回复至小程序6. 持续优化7. Postman请求示例 三、通用AI客…

Visual Studio Add-in开发

https://www.cnblogs.com/kekec/p/10522250.html https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2017/extensibility/vsct-xml-schema-reference?viewvs-2017 https://github.com/search?lC%2B%2B&p2&qvisualstdio&typeReposi…

Android中使用Palette让你的页面UI优雅起来

文章目录 1. 什么是Palette2. 引入Palette3. 使用 Palette3.1 同步方式3.2 异步方式3.3 获取色调值 4. 举例4.1 布局文件 activity_palette_list.xml ⬇️4.2 Activity&#xff1a;PaletteListActivity⬇️4.3 列表Adapter&#xff1a;PaletteListAdapter ⬇️4.4 列表item布局…