什么是axios

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

Features:

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

使用方式有两种

第一种,直接 const axios = require(‘axioa’)后调用api

//Two ways to Send a POST request

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

api:

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios.all(iterable)
axios.spread(callback)

后两个方法用于处理concurrent requests

第二种使用实例化了的对象

axios.create([config])

const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});

Instance methods:

request(config)
get(url[, config])
delete(url[, config])
head(url[, config])
options(url[, config])
post(url[, data[, config]])
put(url[, data[, config]])
patch(url[, data[, config]])
getUri([config])

个人觉得这种特别适用于有很多的service api调用的时候,这样可以统一配置请求的url,如baseURL;

instance({
url: '/info/devices/',
method: 'get'
});

Request Config

好大一篇,好些我都没有用到,也不能明确知道它是干 什么用,有待慢慢的展开学习。

{
url: '/user',
method: 'get', // default
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data return data;
}], // `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
// Do whatever you want to transform the data return data;
}], // `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
// what is a URLSearchParams object
// var paramsString = "q=URLUtils.searchParams&topic=api";
// var searchParams = new URLSearchParams(paramsString);
params: {
ID: 12345
}, // `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
}, // `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier.
// Return a promise and supply a valid response (see lib/adapters/README.md).
adapter: function (config) {
/* ... */
}, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
auth: {
username: 'janedoe',
password: 's00pers3cret'
}, // `responseType` indicates the type of data that the server will respond with
// options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
}, // `onDownloadProgress` allows handling of progress events for downloads
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
}, // `maxContentLength` defines the max size of the http response content in bytes allowed
maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}, // `maxRedirects` defines the maximum number of redirects to follow in node.js.
// If set to 0, no redirects will be followed.
maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
// variable as a comma-separated list of domains that should not be proxied.
// Use `false` to disable proxies, ignoring environment variables.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
}, // `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}

可以通过defaults属性来取得request config里各项的值,还可以重新赋值

更改全局的axios的defaults

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';

更改某个实例的defaults

instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Response Schema

{
data: {},
status: 200,
statusText: 'OK', // `headers` the headers that the server responded with
// All header names are lower cased
headers: {}, // `config` is the config that was provided to `axios` for the request
config: {}, // `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}

当出错时,会进入catch进行错误处理

axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});

配置response.status是多少时,触发reject

axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})

Interceptors

重头戏在最后了

You can intercept requests or responses before they are handled by then or catch.

还是两种途径,全局加、单例加

只展示单例加interceptors的代码吧,可以在这里统一的出处理一些事件,只让前端观注view

const instance= axios.create({
baseURL: 'http://somedomain.com/api/',
timeout: 300000
}) // request interceptors
instance.interceptors.request.use(config => {
//发送请求前,头部加上token值
if (store.getters.token && config.url !== '/login') {
config.headers.common['Authorization'] = ['Bearer', getToken()].join(' ');
} else {
config.headers.common['Authorization'] = '';
}
return config
}, error => {
Promise.reject(error)
}) // respone interceptor
instance.interceptors.response.use(
response => response,
error => {
let msg= '';
if (error.response && error.response.status) {
const status = error.response.status;
switch (status) {
case 401:
router.replace({
path: '/'
});
break;
default:
break;
}
}
if (!error.response) {
msg = '访问超时';
}
console.log(msg );
return Promise.reject(msg); })

什么是promise

在调用一个不能立即返回结果的方法或耗时很长的方法时,promise可以帮助在方法有返回值时返回,用resolve和reject来处理返回结果。

new Promise( function(resolve, reject) {...} /* executor */  );

它有三个状态: pending ,fulfilled, rejected。

resolve对应执行then的参数function.

reject对应执行catch的参数function.

它可以用来配合axios, setTimeout一起使用。

var pro = new Promise((resolve, reject) => {
axios.get({
url:'http://website.com/api/data'
}).then(response => {
resolve(response.data);
}).catch(error => {
reject(error);
})
});
pro.then(data=>{
console.log(data);
}).catch(error=>{
console.log(error);
});

promise还有两个方法,Promise.all / Promise.race

Promise.all(iterable)这个方法返回一个新的promise对象,该promise对象在iterable参数对象里所有的promise对象都成功的时候才会触发成功,一旦有任何一个iterable里面的promise对象失败则立即触发该promise对象的失败。这个新的promise对象在触发成功状态以后,会把一个包含iterable里所有promise返回值的数组作为成功回调的返回值,顺序跟iterable的顺序保持一致;如果这个新的promise对象触发了失败状态,它会把iterable里第一个触发失败的promise对象的错误信息作为它的失败错误信息。Promise.all方法常被用于处理多个promise对象的状态集合

Promise.race(iterable)当iterable参数里的任意一个子promise被成功或失败后,父promise马上也会用子promise的成功返回值或失败详情作为参数调用父promise绑定的相应句柄,并返回该promise对象。

通常而言,如果你不知道一个值是否是Promise对象,使用Promise.resolve(value) 来返回一个Promise对象,这样就能将该value以Promise对象形式使用。

axios和promise的更多相关文章

  1. axios - 基于 Promise 的 HTTP 异步请求库

    axios 是基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用.Vue 更新到2.0之后,作者就宣告不再对 vue-resource 模块更新,而是推荐使用 a ...

  2. 介绍axios和promise

    今天小编为大家带来 axios 和promise的详细讲解,包含 axios的使用方法 多种写法,封装 以及 promise的详细讲解,项目中如何运用等,会一一的为大家讲解清楚. 一.axios的介绍 ...

  3. 解决axios IE11 Promise对象未定义

    在你的项目中安装polyfill Babel Polyfill 按照官网方法安装并引入即可 http://blog.csdn.net/panyox/article/details/76377248

  4. ajax和promise及axios和promise的结合

    链接:https://www.cnblogs.com/mmykdbc/p/10345108.html 链接2:https://blog.csdn.net/UtopiaOfArtoria/article ...

  5. Axios源码阅读笔记#1 默认配置项

    Promise based HTTP client for the browser and node.js 这是 Axios 的定义,Axios 是基于 Promise,用于HTTP客户端--浏览器和 ...

  6. promise应用及原生实现promise模型

    一.先看一个应用场景 发送一个请求获得用户id, 然后根据所获得的用户id去执行另外处理.当然这里我们完全可以使用回调,即在请求成功之后执行callback; 但是如果又添加需求呢?比如获得用户id之 ...

  7. axios(封装使用、拦截特定请求、判断所有请求加载完毕)

    博客地址:https://ainyi.com/71 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 Node.js 中使用 vue2.0之后,就不再对 vue-resource 更新 ...

  8. axios 中文文档(转载)

    axios中文文档 转载来源:https://www.jianshu.com/p/7a9fbcbb1114 原始出处:lewis1990@amoy axios 基于promise用于浏览器和node. ...

  9. vue2.0之axios使用详解

    axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 htt ...

随机推荐

  1. TZOJ:3660: 家庭关系

    描述 给定若干家庭成员之间的关系,判断2个人是否属于同一家庭,即2个人之间均可以通过这些关系直接或者间接联系. 输入 输入数据有多组,每组数据的第一行为一个正整数n(1<=n<=100), ...

  2. Redis入门到高可用(十五)—— HyperLogLog

    一.简介 二.API Demo 三.使用经验

  3. pytorch torchvision对图像进行变换

    class torchvision.transforms.Compose(转换) 多个将transform组合起来使用. class torchvision.transforms.CenterCrop ...

  4. iscroll4升级到iscroll5全攻略笔记

    前段时间在搞移动终端(移动web)的项目,其中需要用到滚动的功能(html的滚动效果不好,且在低版本上不支持).后面上网找了下资料,发现大部分人都在用iscroll4(下面简称v4),下载下来试了下确 ...

  5. vue-awesome-swiper组件不能自动播放和导航器小圆点不显示问题

    from: https://blog.csdn.net/osdfhv/article/details/79062427 <template> <div class="swi ...

  6. Ansible学习实战手记-你想要知道的可能都在这里了

    最近接触了ansible工具,查找了一些资料,也做了一些总结.希望能给刚接触的新手带来一些帮助. 此总结有实际例子,大部分也是从实践中用到才逐一总结的. 当然可能肯定一定会存在一些错误和纰漏,还望大家 ...

  7. 7.mongo python 库 pymongo的安装

    1.Python 中如果想要和 MongoDB 进行交互就需要借助于 PyMongo 库,在CMD中使用命令即可[注意此处是pip3,pip无法安装]: pip3 install pymongo 2. ...

  8. tomcat+apache的集群配置

    背景:项目比较大,用户较多,同一时间,用户在线人数较多,为此,整体架构是lvs(2台)+keepalived(2台)+apache(N台)+tomcat(N台) lvs负责分发请求,所有的web请求经 ...

  9. ASP.NET Core SignalR

    ASP.NET Core SignalR 是微软开发的一套基于ASP.NET Core的与Web进行实时交互的类库,它使我们的应用能够实时的把数据推送给Web客户端. 功能 自动管理连接 允许同时广播 ...

  10. 爬虫----requests模块

    一.介绍 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内 ...