axios和promise
什么是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的更多相关文章
- axios - 基于 Promise 的 HTTP 异步请求库
axios 是基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用.Vue 更新到2.0之后,作者就宣告不再对 vue-resource 模块更新,而是推荐使用 a ...
- 介绍axios和promise
今天小编为大家带来 axios 和promise的详细讲解,包含 axios的使用方法 多种写法,封装 以及 promise的详细讲解,项目中如何运用等,会一一的为大家讲解清楚. 一.axios的介绍 ...
- 解决axios IE11 Promise对象未定义
在你的项目中安装polyfill Babel Polyfill 按照官网方法安装并引入即可 http://blog.csdn.net/panyox/article/details/76377248
- ajax和promise及axios和promise的结合
链接:https://www.cnblogs.com/mmykdbc/p/10345108.html 链接2:https://blog.csdn.net/UtopiaOfArtoria/article ...
- Axios源码阅读笔记#1 默认配置项
Promise based HTTP client for the browser and node.js 这是 Axios 的定义,Axios 是基于 Promise,用于HTTP客户端--浏览器和 ...
- promise应用及原生实现promise模型
一.先看一个应用场景 发送一个请求获得用户id, 然后根据所获得的用户id去执行另外处理.当然这里我们完全可以使用回调,即在请求成功之后执行callback; 但是如果又添加需求呢?比如获得用户id之 ...
- axios(封装使用、拦截特定请求、判断所有请求加载完毕)
博客地址:https://ainyi.com/71 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 Node.js 中使用 vue2.0之后,就不再对 vue-resource 更新 ...
- axios 中文文档(转载)
axios中文文档 转载来源:https://www.jianshu.com/p/7a9fbcbb1114 原始出处:lewis1990@amoy axios 基于promise用于浏览器和node. ...
- vue2.0之axios使用详解
axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 htt ...
随机推荐
- from appium import webdriver 使用python爬虫,批量爬取抖音app视频(requests+Fiddler+appium)
使用python爬虫,批量爬取抖音app视频(requests+Fiddler+appium) - 北平吴彦祖 - 博客园 https://www.cnblogs.com/stevenshushu/p ...
- 数组/Array/Tuple/yield
数组 如果需要使用同一类型的多个对象,就可以考虑使用集合和数组.如果需要使用不同类型的多个对象,可以考虑使用Tuple(元组) 数组的声明 在声明数组时,应先定义数组元素中的类型,其后是一对空方括号和 ...
- 为什么分布式数据库中不使用uuid作为主键?
分布式数据库当然也有主键的需求,但是为什么不直接使用uuid作为主键呢?作为曾经被这个问题困惑过的人,试着回答一下 1. UUID生成速率低下 Java的UUID依赖于SecureRandom.nex ...
- OGG学习笔记05-OGG的版本
刚接触OGG的时候,很容易被众多的版本搞晕,虽然官方有提供各版本对应认证OS和DB的表格. 个人认为一个比较简单的方式,是直接去edelivery.oracle.com下载OGG,选定一个大版本后,这 ...
- Qt 快捷键 复制当前行 向上复制 && 向下复制
网上的答案不一,我的快捷键是默认的配置,未做过修改. 向前复制当前行: Ctrl + Alt + up (向上箭头) 向后复制当前行:Ctrl + Alt + down(向下箭头) 补充一个:Ctrl ...
- Kubernetes应用健康检查
目录贴:Kubernetes学习系列 在实际生产环境中,想要使得开发的应用程序完全没有bug,在任何时候都运行正常,几乎 是不可能的任务.因此,我们需要一套管理系统,来对用户的应用程序执行周期性的健康 ...
- CRT/LCD/VGA Information and Timing
彩色阴极射线管的剖面图: 1. 电子QIANG Three Electron guns (for red, green, and blue phosphor dots)2. 电子束 Electron ...
- win10虚拟桌面使用方法-提高工作效率
任务栏右键 => 显示任务视图按钮 然后坐下角出现的任务视图按钮可以添加虚拟桌面 快捷键: win + ctrl + 左/右 切换桌面 win + tab 打开任务视图 win + ctrl + ...
- 剑指offer(61)序列化二叉树
题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 题目分析 首先拿到题目时候,我先想到的是什么是序列化二叉树?序列化主要就是在前后端交互时候需要转换下,毕竟网络传输的是流式数据(二进制或者文本 ...
- VOC标签转化为YOLO标签
参考darknet自带的voc_label.py import xml.etree.ElementTree as ET import pickle import os from os import l ...