axios post 请求后端参数为null解决方案

先看看官方教学请求写法

axios.post('http://xxx.xxx.xxx.xxx:xxxx/xx', {'id': 'test'}).then(function (res) {
    console.log(res)
  }).catch(function (error) {
    alert(error)
  })

 

结果后端接收到请求后,从HttpServletRequest获取的参数居然是null,这里记录一下,怎样解决这个问题,免得以后忘记,原因可以网上找找

这是后端的接收请求代码

 @RequestMapping(value="/test",method= RequestMethod.POST)
    public String test(HttpServletRequest request){
        String id = request.getParameter("id");
        System.out.println(id);return "";
    }

 

方法1:

在前端发送axios的参数改成一个FromData对象,如下:

var f = new FormData()
f.append('id', 'test')

axios.post('http://xxx.xxx.xxx.xxx:xxxx/xx', f).then(function (res) {
    console.log(res)
  }).catch(function (error) {
    alert(error)
  })

 

方法2:

使用方法1后,发现如果我已经有一个对象,每次请求都需要重新拆开里面的内容,重新放到FormData不就和麻烦,所以就找来了qs模块帮忙实现对象转换

第一步就是安装qs

npm install qs --save-dev

 

第二步,引用qs

import qs from 'qs'

//Vue全局对象可用
Vue.prototype.$qs = qs

 

第三步调用

var test = {'id', 'test'}

//这里的this是Vue对象, axios.post(
'http://xxx.xxx.xxx.xxx:xxxx/xx', this.$qs.stringify(test)).then(function (res) { console.log(res) }).catch(function (error) { alert(error) })

 

总结:网上还有很多方式,不过本人觉得这个方式最容易,改动最少,所以就使用以上两种方法了,使用这两种方法就能后台就能成共获取到数据了

posted @ 2019-03-08 16:19  长命百岁  阅读(6309)  评论(0编辑  收藏  举报