Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
npm安装
npm install axios
使用cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
main.js
import axios from 'axios' Vue.prototype.$axios = axios
挂载到vue上在页面中使用就可以this.$axios.get()
全局axios默认值设置
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; axios.defaults.withCredentials = true// 跨域
拦截器
在请求或响应被 then 或 catch 处理前拦截它们。 // 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(function (response) { // 对响应数据做点什么 return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); });
扩展知识
http请求参数之Query String Parameters、Form Data、Payload
在与server端进行数据传递时,通常会用到GET、POST方法进行参数提交,而参数提交的方式,通常取决于server端对数据的接收方式。
Query String Parameters
当发起一次GET请求时,参数会以url string的形式进行传递。即?
后的字符串则为其请求参数,并以&
作为分隔符。
axios结合qs请求,如this.$axios.get('/log/selectEmqLogListByPage?' + qs.stringify(this.param))
// General Request URL: http://foo.com?x=1&y=2 Request Method: GET // Query String Parameters x=1&y=2
Form Data
当发起一次POST请求时,若未指定content-type,则默认content-type为application/x-www-form-urlencoded。即参数会以Form Data的形式进行传递,不会显式出现在请求url中。
// General Request URL: http://foo.com Request Method: POST // Request Headers content-type: application/x-www-form-urlencoded; charset=UTF-8 // Form Data x=1&y=2
Payload
payload是一种以JSON格式进行数据传输的一种方式。content-type为application/json,则参数会以Request Payload的形式进行传递(显然的,数据格式为JSON),不会显式出现在请求url中。
// General Request URL: http://foo.com Request Method: POST // Request Headers content-type: application/json; charset=UTF-8 // Request Payload x=1&y=2
// General Request URL: http://foo.com Request Method: POST // Request Headers content-type: multipart/form-data; charset=UTF-8 // Request Payload ------WebKitFormBoundaryAIpmgzV8Ohi99ImM Content-Disposition: form-data; name="x" 1 ------WebKitFormBoundaryAIpmgzV8Ohi99ImM Content-Disposition: form-data; name="y" 2 ------WebKitFormBoundaryAIpmgzV8Ohi99ImM--
其中,WebKitFormBoundaryAIpmgzV8Ohi99ImM
为浏览器随机生成的boundary
,作为分隔参数,作用等同于&
。
let formData = new FormData() formData.append('deviceType', this.updateParam.deviceType) formData.append('file', this.updateParam.file) this.$axios.post('/firmware', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
qs
npm install qs
import qs from 'qs'
参考文档
并发请求暂未使用过
官方http://www.axios-js.com/zh-cn/docs/
扩展参考文档