Axios

What is

Axios is promise based HTTP client for the browser and node.js.

Promise

Installing

  • Using npm:
$ npm install axios
  • Using bower:
$ bower install axios
  • Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Example

GET

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

POST

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

注意

实际使用时,axios 使用post方式传递参数,后端接受不到

  • main.js 里 设置配置,修改 Content-Type
import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$axios = axios;
  • 在组件vue里
const url ='http://****你的接口****';
var params = new URLSearchParams();
params.append('key1', 'value1');       //你要传给后台的参数值 key/value
params.append('key2', 'value2');
params.append('key3', 'value3');
this.$axios({
    method: 'post',
    url:url,
    data:params
}).then((res)=>{
});

实际问题

post 传递 json

前端传递参数 json,但是因为 json 中包含特殊字符 ',导致传递失败。

去网上查询,说是使用 encodeURIComponent,但是实际测试无效,后来验证使用 formdata

FormData对象用以将数据编译成键值对,以便用XMLHttpRequest来发送数据。

其主要用于发送表单数据,但亦可用于发送带键数据(keyed data),而独立于表单使用。

如果表单 enctyp e属性设为 multipart/form-data,则会使用表单的 submit() 方法来发送数据,从而,发送数据具有同样形式。

  • 实例
let formdata = new FormData();
formdata.append('partyIds', partyIds);

API.pms.traderList(formdata).then(res => {
  this.counterTrader = res.data;
}).catch(res => {
  this.$Message.error('获取对手方交易员出错!');
});

其中交易员列表函数为:

export function traderList(params) {
  return request({
    url: '/pms/trader/traders',
    method: 'post',
    data: params
  });
}

post 请求后端接收的值为空

场景

axios 发送 post 请求,后端接收到了,但是属性值都是空的。

后端

@RequestMapping("/add")
@ResponseBody
public BaseResp add(final User user) {
    user.setUserId(IdWorker.get32UUID());
    userService.insert(user);
    return RespUtil.success();
}

前端

var user = {
    userId: this.addForm.userId,
    userName: this.addForm.userName,
    remark: this.addForm.remark
}
axios.post('/user/add', user).then(function (response) {
        console.log(response);
}).catch(function (error) {
        console.log(error);
});

解决方案

看了一篇比较详细的介绍:axios 发 post 请求,后端接收不到参数的解决方案

尝试了几种引入 qs 的方案都失败了,于是采用比较直接的方式,后端加一个 @RequestBody 注解。

@RequestMapping("/add")
@ResponseBody
public BaseResp add(@RequestBody final User user) {
    user.setUserId(IdWorker.get32UUID());
    userService.insert(user);
    return RespUtil.success();
}

其他保持不变,可以正常接收。

this 不指向 vue 的问题

在请求回调中,this 实际上是不指向 vue 的,这导致了很多问题。

解决方案

请求之前,使用 _this 保存 vue 的 this 信息。

//axios 中的 this 并不指向 vue
var _this = this;
axios.post('/user/list', req).then(function (response) {
    if(response.data.respCode === '0000') {
        _this.tableData = response.data.list;
        _this.page.total = response.data.total;
    } else {
        ELEMENT.Message.error(response.data.respMessage);
    }
}).catch(function (error) {
    ELEMENT.Message.error("请求失败");
    console.log(error);
});

拓展阅读

QS

参考资料

https://blog.csdn.net/qq_27409289/article/details/71156459

https://blog.csdn.net/jluzh04140717/article/details/70193932

axios 发 post 请求,后端接收不到参数的解决方案