axios 默认值 & 建立实体 & 错误侦测

此笔记版本 v0.19.0

axios 基本用法 与 Config 详解

建立 axios 实体 好处 (axios.create)

统一套用 Config统一管理 API,日后修改容易 (分开档案、Import)减少 URL 冗长更易读 (baseURL运用)

建立 axios 实体 範例

api.js 统一管理 API Call Url使用 import 引入该 API
  // 此为 api.js 档案 (统一管理 API)  import axios from 'axios'  const userRequest = axios.create({    baseURL: 'http://localhost:3000',    headers: { 'Content-Type': 'application/json' },  })  // 可以统一管理 API Call  const postFunc = data => userRequest.post('/users', data)  const getFunc = url => userRequest.get(url)
  // 要使用该 api 的档案,使用 import将方法载入  import { postFunc, getFunc } from 'api.js';   run()  async function run() {    try {      // 可以连 URL 都进行封装      const post1 = await postFunc({ name: '123' })      const post2 = await postFunc({ name: '456' })            // 上面的方法更佳 API 应存在同一个档案作管理      const post3 = await userRequest.post('/users', { name: '789' })            const get = await getFunc('/users')      console.table(get.data)    } catch (error) {      throw new Error(error)    }  }

配置的优先顺序 (低到高)

实体建立时的配置 (最低)覆盖原始设定发送请求的 config 参数 (最高)
  // 不设定即採用默认值 timeout 为 0  let instance = axios.create()  // 覆盖原始 instance  instance.defaults.timeout = 2500  // 发送请求的 config  instance.get('/longRequest', {    timeout: 5000 // 採用此 config 设定  })

全域默认值 (可略)

可以利用 console.log(axios.default) 查询内容axios.defaults.common['表头名'] 通用设定axios.defaults.post['表头名'] post方法用设定
  console.log(axios.default)  axios.defaults.baseURL = 'url'  axios.defaults.headers.common['Content-Type'] = '~'  axios.defaults.headers.post['Content-Type'] = '~'

错误侦测 (Handling Errors)

config: validateStatus
  // 自定 reject 状态码範围  const config = {    validateStatus(status) { return status >= 200 && status < 300 },  }
  axios.get('/user/12345')    .catch((error) => {      if (error.response) {        // 当状态码不在 validateStatus 设定的範围时进入        // 有 data / status / headers 参数可用        console.log(error.response.status)      } else if (error.request) {        // 发送请求,但没有接到回应        // error.request is an instance of XMLHttpRequest in the browser         // and an instance of http.ClientRequest in node.js        console.log(error.request)      } else {        // 在设定 request 时出错会进入此        console.log('Error', error.message)      }      console.log(error.config)    })

档案上传範例

将档案转成 Blob 并使用 FormData API 格式传输Content-Type 必须设成 multipart/form-data

建立 remote img

  axios({    method: 'get',    url: 'http://bit.ly/2mTM3nY',    responseType: 'stream',  })    .then((response) => {       response.data.pipe(fs.createWriteStream('Img.jpg'))     })

以下 本人太菜还没用过 用到再回来补

拦截器 (Interceptors)

拦截 请求/回应 于 then/catch 前

取消 (Cancellation)

利用 cancel token 取消请求

使用 application/x-www-form-urlencoded

axios 预设使用 JSON

参考资料

axios Github
axios 中文文档(有些省略的)
axios小笔记
使用Axios你的API都怎么管理?


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章