You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Vue.js+Axios调用Spring MVC接口返回415错误的问题排查求助

Axios POST请求返回415错误,请求头未正确携带application/x-www-form-urlencoded

问题描述

我正在使用Vue.js、Axios和Spring进行开发。前端页面中的Axios代码如下:

axios({
  method: 'post',
  url: '/user/info',
  params: {
    '_csrf' : document.getElementById('csrf_id').value,
    'name' : 'job',
    'age' : '25',
  },
  headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});

后端接收请求的Spring代码如下:

@Controller
@RequestMapping("/user")
public class UserInfo {
    @ResponseBody
    @PostMapping(value = "/info", consumes = "application/x-www-form-urlencoded", produces = "application/json" + ";charset=utf8")
    public String info(@RequestParam(value = "name") String name, @RequestParam(value = "age") String age) {
        System.out.println(name);
        System.out.println(age);
        return "ok";
    }
}

当Axios向后端发送请求时,服务器返回415响应,且请求头中缺失application/x-www-form-urlencoded内容类型,我怀疑问题根源在此,想请教我哪里操作有误?


回答

嘿,我来帮你排查下这个问题!你遇到的415错误确实和请求的内容类型以及数据传递方式有关,具体问题和修复方法如下:

1. 错误核心:用params传递POST数据是错的

Axios里的params是用来设置URL查询参数的,不管你用GET还是POST,用params的话参数都会拼在URL后面,请求体是空的。而你的Spring后端明确要求接收application/x-www-form-urlencoded格式的请求体数据,这就导致后端找不到符合要求的请求体,直接返回415。

另外,即使你手动设置了Content-Type头,当请求体为空时,浏览器或者Axios可能会忽略这个头,这就是你看到请求头里缺失该类型的原因。

2. 修复步骤

步骤1:把params替换成data

POST请求的表单数据应该放在data字段里,这样数据才会被放到请求体中。

步骤2:将数据序列化为x-www-form-urlencoded格式

Axios默认会把JavaScript对象序列化为JSON格式,这和后端要求的格式不匹配。你需要把数据转换成URL编码的格式,有两种常用方式:

方式一:使用原生URLSearchParams
const formData = new URLSearchParams();
formData.append('_csrf', document.getElementById('csrf_id').value);
formData.append('name', 'job');
formData.append('age', '25');

axios({
  method: 'post',
  url: '/user/info',
  data: formData,
  headers: {
    'Accept': 'application/json'
    // 这里可以不用手动设置Content-Type,因为URLSearchParams会自动触发Axios设置正确的头
  }
});
方式二:使用qs库(更适合复杂对象)

如果你的数据结构比较复杂,推荐使用qs库来序列化:

import qs from 'qs';

axios({
  method: 'post',
  url: '/user/info',
  data: qs.stringify({
    '_csrf' : document.getElementById('csrf_id').value,
    'name' : 'job',
    'age' : '25',
  }),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
  }
});

3. 后端代码无需修改

你的Spring后端代码是没问题的,@RequestParam可以正确接收x-www-form-urlencoded格式的请求体参数,只要前端正确发送数据即可。


内容的提问来源于stack exchange,提问作者Steve Jobs

火山引擎 最新活动