一、能够使用自定义配置新建一个 axios 实例: axios.create([config])ios
var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: { 'X-Custom-Header': 'foobar' auth: { // auth表示使用 HTTP 基础验证,并提供凭据 username: 'janedoe', password: 's00pers3cret' } } });
auth设置将覆写掉任意使用 headers
(axios.defaults.headers.xxx)设置的自定义 Authorization
头json
二、为方便起见,axios为全部支持的请求方法提供了别名:axios
axios.get(url\[, config\]) axios.post(url\[, data\[, config\]\])
const ax = axios.create() function download(url, params) { ax.get({ methods: 'get', url, params, responseType: 'blob' // 表示服务器响应的数据类型,能够是 //'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认json }).then({ const hd = resp.headers['content-disposition'] let fileName = 'download'; if (hd) { const temp = hd.split(';')[1] fileName = decodeURIComponent(temp.split('=')[1]) } const resType = res.headers['Content-Type'] if (resType.indexOf('application/json') != -1) { alert('后台返回的是JSON报错信息') } else { // 非IE下载 if ('download' in document.createElement('a')) { let link = document.createElement('a') link.href = window.URL.createObjectURL(res.data) // 建立下载的连接 link.download = filename // 下载后文件名 link.style.display = 'none' document.body.appendChild(link) link.click() // 点击下载 window.URL.revokeObjectURL(link.href) // 释放掉Blob对象 document.body.removeChilc(link) // 下载完成移除元素 } else { // IE10+下载 window.navigator.msSaveBlob(res.data, fileName) // responseType: 'blob'指定了res.data为Blob对象 } } }) }
POST方式下载:api
ax.post(url, params, { responseType: 'blob' }).then(res => { // 同上 })