项目用到axios,记录下简单用法
1.普通get请求
axios.get('http://127.0.0.1:8080/test/delUser?userId='+id) .then((response) => { console.log(response.data);//请求的返回体 }) .catch((error) => { console.log(error);//异常 });
参数传递也可以这样写
axios.get('http://127.0.0.1:8080/test/delUser',{ params: { userId: id, } }) .then((response) => { console.log(response.data);//请求的返回体 }) .catch((error) => { console.log(error);//异常 });
2.post请求写法
axios.post('http://127.0.0.1:8080/test/login', { name: "admin", pwd: "123456" }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
这时候的post请求使用这这种请求,Spring MVC中直接@RequestParam 接收参数是接受不到的
打开浏览器开发者工具会发现Request-Headers的Content-Type是application/json;charset=UTF-8
如果不想使用application/json的解决方式:
let param = new URLSearchParams();//使用URLSearchParams传参数 param.append("name", "admin"); param.append("pwd", "123456"); axios.post('http://127.0.0.1:8080/test/login',param) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3.一次性并发多个请求
function getListOne(){ return axios.get('http://127.0.0.1:8080/test/getListOne'); } function getListTwo(){ return axios.get('http://127.0.0.1:8080/test/getListOne'); } axios.all([getListOne(),getListTwo()]) .then(axios.spread(function(acct,perms){ //两个请求都成功触发这个函数,两个参数代表两次请求返回的结果 }))
4.PS:axios不支持同步请求,可以使用请求成功之后再操作的方式代替同步请求