当前位置:   article > 正文

Vue 前端 put 或 post 请求发送到 Spring Boot 后端无法接收到数据的解决方法_vue method: 'put' 不生效

vue method: 'put' 不生效

项目场景:

Vue前端向Spring Boot后端发送put或post请求,使用axios

问题描述:

Vue前端向Spring Boot后端发送数据,使用的是post或是put请求时,后端获取不到数据,显示为空

原因分析:

axios默认post请求格式为json,但spring boot默认不使用json格式解析

解决方案:

1、后端处理

在controller方法中的参数前面加入@RequestBody
例:

@PostMapping
public void add(@RequestBody Obiect o) {
    System.out.println(o);
}
  • 1
  • 2
  • 3
  • 4

2、前端处理

将表单数据格式化为字符串

先安装qs库

npm i qs
  • 1

axios中的配置文件中加入如下配置即可

import Qs from "qs";
request.interceptors.request.use(config => {
    if (config.method === 'put' || config.method === 'post') {
        config.headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        config.data = Qs.stringify(config.data)
    }
    return config
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50103
推荐阅读
相关标签
  

闽ICP备14008679号