前端通过axios调用后端接口
async getUserByUsername(query) {
if (query !== "") {
this.selectLoading = true;
// api.selectUserByUsername封装了接口的axios请求
const { data: res } = await api.selectUserByUsername(query);
console.log(res);
}
},
axios接口封装:
selectUserByUsername(query) {
return axios.post(path.userSelectByUsername, query);
},
后端接口接收String
类型的message
@RequestMapping(value = "/selectByUsername", method = RequestMethod.POST)
public RestResponse<List<KeyValue>> selectByUsername(@RequestBody String username) {
// xxx...
}
在测试过程中发现当query
传s
时,后端接收到的值为s=
【原因】
在封装axios请求时没有设置content-type
的值,因此为默认的application/x-www-form-urlencoded
,这种数据结构是一种键值对数据结构,在传输的时候将传的值当成了键 加了一个=
, 值为空 所以传输到后端 会多出来一个 =
如果将
content-type
的值设置为application/json
,后端在接收时会显示为"s"
【解决办法】
将content-type
的值设置为text/plain
,后端在接收时会显示为"s"
selectUserByUsername(query) {
return axios.post(path.userSelectByUsername, query, {
headers: {
"Content-Type": "text/plain",
},
});
},
将参数格式设置为纯文本,可以解析后端参数出现格式不对的问题