axios 介绍
依赖 ES6 Promise,若不支援请使用 Polyfill支援 Promise API可取消请求 (Promise 无法)自动转换 JSONaxios 实体建立此笔记版本 v0.19.0
大纲
安装 / GET / POST 基础用法axios 一般写法axios API 写法axios 一次发送多个请求 (all)axios async 範例axios config 详解安装
npm 安装或挂 cdn $ npm install axios
GET / POST 基础用法
注意!!! axios 回传并非直接是资料console.log(res) 类似 request Object
内容包含: data / status / statusText / headers / config
// 网址带参数 或 传入 params 物件 axios.get('url/users?ID=123') axios.get('url/users', { params: { ID: 123 } }) .then((res) => { console.table(res.data) }) .catch((error) => { console.error(error) }) .finally(() => { /* 不论失败成功皆会执行 */ }) // 资料由后方物件带入 axios.post('url/users', { name: 'Mark' }) .then((res) => { console.table(res.data) }) .catch((error) => { console.error(error) })
axios 一般写法
axios(config 物件)then result 回传类似 reponseObject,其中 data 才是要的资料下面会介绍 如何统一使用 config 更易管理 axios({ method: 'get', baseURL: 'http://localhost:3000', url: '/users', 'Content-Type': 'application/json',}) .then((result) => { console.log(result.data) }) .catch((err) => { console.error(err) })
axios API 写法
使用以下写法 不需要再将 url、method、data 写在 config 裏面config 用来撰写 表头、一些设定 (下有详解) axios(config) axios.request(config) // 与上相同功能 axios.get(url, config) axios.delete(url, config) // 功能与 GET 相同,但无 response body axios.head(url, config) axios.post(url, data, config) axios.put(url, data, config) axios.patch(url, data, config) // 用来发送探测请求,确认该地址採用的协定、要求的表头 axios.options(url, config) // 预先检查发送的请求是否安全
同时发送多个请求 all & spread
类似 Promise All 用法注意 then 后接 axios.spread若直接用 如下 会得两结果合併的阵列 (自行测试的结果)then( res => console.log(res) )
axios.all([funcA(), funcB()]) .then(axios.spread((acct, perms) => { // axios 回传的资料在 data 属性 console.table('FuncA 回传结果', acct.data) // fetch 资料可以先在 function 内作 json() console.table('FuncB 回传结果', perms) })) .catch((err) => { console.error(err) }) function funcA() { return axios.get('http://localhost:3000/users/1') } function funcB() { return fetch('http://localhost:3000/users/2', { method: 'GET', headers: { 'Content-Type': 'application/json' }, }).then(res => res.json()) }
搭配 async
利用 try catch 作错误侦测try 包裹所有 await 有错误则进入 catch getUsers() async function getUsers() { try { const post = await postUsers() const get = await axios.get('http://localhost:3000/users') const { data } = get // 资料在 data 属性 console.dir(get) // 回传类似 RequestObject console.table(data) } catch (error) { throw new Error(error) } }
axios config 请求配置
可加入自订表头 (Header)adapters 用法 const config = { url: '/users', // 只有此为必需 method: 'post', // 大小写皆可 headers: { 'Content-Type': 'application/json' }, // 添加在 url 前面,除非 url 为绝对路径 baseURL: 'http://localhost:3000' // 主要传送的资料 (只用于 PUT、POST、PATCH ) // 在没有 transformRequest 情况下资料型别有限制 (下有补充) data: { name: 'test', title: 777 }, // params 注意此不等同于 data // 此为 URL 上要代的参数 ~url?ID=123 params: { ID: 123 } // 序列化参数 ??? paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, maxContentLength: 2000, // 限制传送大小 // 请求时间超过 1000毫秒(1秒),请求会被中止 timeout: 1000, // 选项: 'arraybuffer', 'document', 'json', 'text', 'stream' // 浏览器才有 'blob' , 预设为 'json' responseType: 'json', // 伺服器回应的数据类型 // 伺服器回应的编码模式 预设 'utf8' responseEncoding: 'utf8', // 在上传、下载途中可执行的事情 (progressBar、Loading) onUploadProgress(progressEvt) { /* 原生 ProgressEvent */ }, onDownloadProgress(progressEvt) { /* 原生 ProgressEvent */ }, // 允许自定义处理请求,可让测试更容易 (有看没懂..) // return promise 并提供有效的回应 (valid response) adapter (config) { /* 下方章节 补充详细用法 */ }, }
Config: 验证 & Token
withCredentials (实用!!)authvalidateStatusxsrfCookieName / xsrfHeaderNameconst config = { // 用来判断是否为 跨域存取 (cross-site Access-Control requests) // 等同 Access-Control-Allow-Credentials 表头 // 用来解决 CORS withCredentials: false, // default // 必须提供 credentials (Cookie) // 等同 Authorization 表头 // 如果使用 token 应去 header 设置 Authorization 而非使用此 auth: { username: 'Mark', password: 123 } // 用来判断是否解析 Promise 的 状态码範围 validateStatus: function (status) { return status >= 200 && status < 300; // default }, // xsrf token 的 Cookie名 / Header名 xsrfCookieName: 'XSRF-TOKEN', // default xsrfHeaderName: 'X-XSRF-TOKEN', // default // 用来取消请求的 token (下详) cancelToken: new CancelToken(function (cancel) { })}
data 的资料型别
在没有 transformRequest 情况下资料型别有限制可在 transformRequest 中作资料转换 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream
Config: 资料处理
发送前 transformRequest使用前 transformResponse只用于 POST、PUT、PATCH const config = { // 资料发送至伺服器前,可作资料处理 // 阵列中最后的函式必须返回字串、ArrayBuffer、Stream transformRequest: [function (data) { // 作资料转换 return data; }], // 在进入 then / catch 前可作资料处理 transformResponse: [function (data) { // 作资料转换 return data; }], }
Config: Proxy 代理
定义 代理伺服器的 Host、Port号auth 代表 HTTP Basic auth 应用于连接代理,并提供 credentials会设置 Proxy-Authorization 表头还有更详细的参数设定,有需要在查 Github const config = { proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, }
node.js 相关 config
maxRedirects 定义 node.js 中要遵循的重定项最大数量socketPath 定义 node.js 用的 UNIX SockethttpAgent / httpsAgent const config = { // 设为 0,则不会重定向 maxRedirects: 5, // default // Ex: '/var/run/docker.sock' 传请求给 docker daemon // socketPath(优先权较高) & proxy 择一使用 socketPath: null, // default // 用于 node.js中执行 http/https的自定义代理 // 默认不启用,可配置成 keepAlive httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), }
参考资料
axios Github
axios 中文文档(有些省略的)
axios小笔记
使用Axios你的API都怎么管理?