axios作为一个基于promise的网络请求库,它同时支持浏览器和node环境,是我们开发中常用的一个库
?
它的一些特性:
?
?
搭建一个本地服务
npm install -g json-serverdb.json
{ "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" }}运行服务
json-server --watch db.json服务搭建完毕,就可以从本地访问数据
GET /postsGET /posts/1POST /postsPUT /posts/1PATCH /posts/1DELETE /posts/1axios(config);axios(url[,config]);最基础的使用方法,引入了axios库就可以直接使用,核心在于config配置,如果没有传入config,就是用默认的
axios({ url: 'http://localhost:3000/posts', method: 'get'});axios('http://localhost:3000/posts', { method: 'post', data: {a:12}})前面介绍了axios的核心方法,可以满足所有请求方法类型[get, post, delete...],不过也有它的别名方法,是为了方便简写,实际上也是调用axios(config),有如下别名方法:
有这样一种场景,一个项目需要请求不同域名的数据:
有没有办法让axios区分这两个请求地址,并分别发送请求呢?
?
这里我们就可以用到axios的实例(instance),通过axios.create()创建,两个实例单独配置,互不影响
// 通过axios.create创建出一个新的单独实例,不和其他实例产生影响let axiosA = axios.create({ // 根路径,以后的请求地址都会拼接上这个地址 baseUrl: 'http://www.a.com/api',});// 这里的请求地址最终为:http://www.a.com/api/getTotalaxiosA.get('/getTotal').then(response=>{});// =============================================================let axiosB = axios.create({ // 根路径,以后的请求地址都会拼接上这个地址 baseUrl: 'http://www.b.com/post',});// 这里的请求地址最终为:http://www.b.com/post/getNameaxiosB.get('/getName').then(response=>{});?
axios的配置项比较多,不过大多数都有默认配置,我们就看一些常用的配置,具体的可以参照官方文档
{ url: '/user', // 请求地址 method: 'get', // 如果没有指定method,默认get baseURL: 'https://some-domain.com/api/', // 请求根路径 transformRequest: [function (data, headers) { // 请求数据转换器 return data; }], transformResponse: [function (data) { // 响应数据转换器 return data; }], headers: {'X-Requested-With': 'XMLHttpRequest'}, // 请求头 params: { // 请求参数 ID: 12345 }, data: { // post提交数据 firstName: 'Fred' }, timeout: 1000, // default is `0` (no timeout) adapter: function (config) { // 适配器,识别浏览器端还是node端 /* ... */ }, auth: { username: 'janedoe', password: 's00pers3cret' }, responseType: 'json', // default responseEncoding: 'utf8', // default maxContentLength: 2000, maxBodyLength: 2000, maxRedirects: 5, // default cancelToken: new CancelToken(function (cancel) { }), // ...}axios.get('http://localhost:3000/posts').then(response=>{ console.log(response);})当我们请求成功后,response的响应结果到底是怎样的?
{ data: {}, // 请求成功的返回数据 status: 200, // 状态码 statusText: 'OK', // 状态描述 headers: {}, // 请求头 config: {}, // config配置项 request: {} // XMLHttpReqest对象}一些通用的配置项,每次都写很麻烦,就通过全局的方式写一次即可,比如headers头信息,baseUrl等
axios.defaults.baseURL = 'https://api.example.com';axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;设置好以后,请求就会有这些默认配置
// https://api.example.com/aaxios.get('/a');假设我又有一个新的请求了,不想用这个baseUrl地址,我们完全可以通过实例的配置重新覆盖全局配置
let axios2 = axios.create({ baseUrl: 'www.baidu.com'});// www.baidu.com/baxios2.get('/b');这里有一个要注意点,关于config的优先级谁的最高?从低到高
何为拦截器?
你可以在这个请求发起之前(request interceptor),和响应数据之后(response interceptor)进行拦截处理
?
请求拦截器1(config) // 函数里面进行处理后,需要返回config请求拦截器2(config) // 函数里面进行处理后,需要返回config...发起数据请求(真实请求)响应拦截器1(response) // 函数里面处理后需要返回response响应拦截器2(response) // 函数里面处理后需要返回response...返回给用户如何使用
axios.interceptors.request.use(function success(config){ // 处理数据 return config;}, function fail(error){ return Promise.reject(error);});axios.interceptors.response.use(function success(response){ // 处理数据 // response.data = JSON.parse(response.data); return response;}, function fail(error){ return Promise.reject(error);});执行流程就如上所示,请求拦截器request会放到 真实请求的前面, 响应拦截器会添加到 真实请求的后面