目录
请求配置(Axios 中文使用 - 简书 (jianshu.com)):
axios 简介
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
一、安装
1、 利用npm安装 npm install axios --save
2、 利用bower安装 bower install axios --save
3、 直接利用cdn引入 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
二、配置路径
其中的baseServer、baseServerPort、baseURL等基本路径配置可以定义在config.js里面进行定义。在axios.js面可直接import,提高项目的代码复用性。
三、axios文件解读
import与export:模块是独立的文件,该文件内部的所有的变量外部都无法获取。如果希望获取某个变量,必须通过export输出,并通过import引进。
import:
import axios from 'axios';
import {
baseURL
} from '@/config.js';
import router from "../router";
export:
创建axios自定义实例默认值
注意到该Axios实例是要应用于该axios文件的实例
export const Axios = axios.create({
timeout: 10 * 1000,
});
执行post请求(同样的方式得到get的请求执行方法):
axios({
method: 'post',
url: url,
data: data,
headers: {
},
})
.then((response) => {
})
.catch((error) => {
});
执行多个并发请求:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
请求配置(Axios 中文使用 - 简书 (jianshu.com)):
{
url: '/user',
method: 'get', // 默认是 get
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data) {
return data;
}],
transformResponse: [function (data) {
// 对 data 进行任意转换处理
return data;
}],
// `headers` 是即将被发送的自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是即将与请求一起发送的 URL 参数
// 必须是一个无格式对象(plain object)或 URLSearchParams 对象
params: {
ID: 12345
},
// `paramsSerializer` 是一个负责 `params` 序列化的函数
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data: {
firstName: 'Fred'
},
// `timeout` 指定请求超时的毫秒数
// 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 1000, //(0 表示无超时时间)
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // 默认的
// `adapter` 允许自定义处理请求,以使测试更轻松
// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默认的
// `responseEncoding`表示用于响应的编码
// 注意: 当responseType是stream时或者client-side请求时,配置无效
responseEncoding: 'utf8', // 默认的
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认的
// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// 对原生进度事件的处理
},
// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
},
// `maxContentLength` 定义允许的响应内容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolved; 否则,promise 将被 rejected
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认的
},
maxRedirects: 5, // 默认的
socketPath: null, // 默认的
// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
// `keepAlive` 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定义代理服务器的主机名称和端口
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
cancelToken: new CancelToken(function (cancel) {
})
}
响应结构:
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 服务器响应的头
headers: {},
// `config` 是为请求提供的配置信息
config: {}
}
请求拦截器和相应拦截器的结构(此处只做请求拦截器的结构):
作用在请求或响应被 then 或 catch 处理前拦截它们
//请求拦截器
Axios.interceptors.request.use(config => {
//若存在这样的token,则从本地存储取出
if (localStorage.token) {
config.headers.Authorization = localStorage.getItem("token")
}
if (localStorage.intranetURL) {
config.url = localStorage.getItem("intranetURL") + config.url
} else {
config.url = baseURL + config.url
}
console.log(config.url)
return config
}, error => {
return Promise.reject(error)
});
axios的全局注册:
使用install(vue)的方法将Axios进行全局注册,该Axios实例可以在全局当中得到复用!
export default {
install(Vue) {
Object.defineProperty(Vue.prototype, '$Axios', {
value: Axios
})
}
}