先看看官方教學請求寫法
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) })
總結:網上還有很多方式,不過本人覺得這個方式最容易,改動最少,所以就使用以上兩種方法了,使用這兩種方法就能后台就能成共獲取到數據了