解决axios.post 请求HttpServletRequest.getParameter获取不到值
时间: 2024-05-13 15:14:07 浏览: 10
如果你使用axios.post发送的请求,后端使用HttpServletRequest.getParameter获取不到值,有可能是因为axios的默认Content-Type是application/json,而不是application/x-www-form-urlencoded,导致参数无法传递。你可以尝试设置axios的Content-Type为application/x-www-form-urlencoded,如下所示:
```
axios({
method: 'post',
url: '/your-url',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
key1: value1,
key2: value2,
// ...
}
})
```
如果你使用的是Vue.js,可以在main.js中全局配置axios的Content-Type,如下所示:
```
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
```
同时,你也需要在后端获取参数时使用相应的方式,如下所示:
```
BufferedInputStream buf = new BufferedInputStream(request.getInputStream());
byte[] reqData = new byte[request.getContentLength()];
buf.read(reqData);
String reqBody = new String(reqData, "utf-8");
Map<String, String> paramMap = JSON.parseObject(reqBody, new TypeReference<Map<String, String>>(){});
String paramValue = paramMap.get("paramName");
```