2025-03-29 14:35:49 +08:00

8.5 KiB
Executable File
Raw Blame History

Axios

Axios 是一个基于 promise 的 HTTP 库

简单理解: 本质上也是对原生XHR的封装, 用来替代JQuery ajax, 符合MVVM

中文文档: https://axios-http.com/zh/

安装

$ npm install axios

引入

<script>
improt axios from 'axios'
</script>

GET请求

语法:

// 无参请求
axios.get(地址) 
.then(请求成功的回调)
.catch(请求失败的回调)

// 带参请求--直接在url拼接
axios.get(地址?参数=&参数=.....)
.then(请求成功的回调)
.catch(请求失败的回调)

// 带参请求,使用对象来传递参数
axios.get(地址,{
	params:{参数}    //params固定写法
})
.then(请求成功的回调)
.catch(请求失败的回调)

示例

methods: {
    getData1 () {
        axios.get('http://127.0.0.1:3000/post')
            .then(function (res) {
            console.log(res);
        })
            .catch(function (err) {
            console.log(err)
        })
    },
        getData2 () {
            axios.get('http://127.0.0.1:3000/post', {
                params: {
                    pageIndex: 1,
                    pageSize: 2
                }
            })
                .then(function (res) {
                console.log(res);
            })
                .catch(function (err) {
                console.log(err)
            })
        }
}

POST请求

语法:

axios.post(地址,{参数})
.then(请求成功的回调)
.catch(请求失败的回调)

示例

methods: {
    login () {
        axios.post('http://127.0.0.1:3000/login', this.user)
            .then((res) => {
            console.log(res);
        })
            .catch((err) => {
            console.log(err);
        })
    }
}

添加token

axios请求中添加token应在header中添加的token使用Authorization属性字段 一般在请求拦截器中添加

{
    url: '/sys/profile',
    method: 'POST'
    // headers: {
    //   Authorization: `Bearer ${store.getters.token}`
    // }
    // 在请求拦截器注入请求头
  }

API

axios(config)

可以通过向 axios 传递相关配置来创建请求:

axios({
    method: 'get', // 设置请求方式
    // url: 'http://127.0.0.1:3000/post',
    url: '/post',// 请求资源路径
    baseURL: 'http://127.0.0.1:3000',
    params: {},//get请求方式的参数post方式使用data
})
    .then((res) => {
    console.log(res);
})
    .catch((err) => {
    console.log(err);
})

配置默认值

全局默认值

import axios from 'axios'
axios.defaults.baseURL = 'http://127.0.0.1:3000'
export default axios

自定义实例默认值

import axios from 'axios'
// 添加统一配置
export default axios.create({
    baseURL:'http://localhost:8080/api/v1/',
    headers:{token传递}
})

可用的配置

/可用的配置项如下:
  // `auth` HTTP Basic Auth
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` 表示浏览器将要响应的数据类型
  // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  // 浏览器专属:'blob'
  responseType: 'json', // 默认值

  // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
  // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // 默认值

  // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
  xsrfCookieName: 'XSRF-TOKEN', // 默认值

  // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值

  // `onUploadProgress` 允许为上传处理进度事件
  // 浏览器专属
  onUploadProgress: function (progressEvent) {
    // 处理原生进度事件
  },

  // `onDownloadProgress` 允许为下载处理进度事件
  // 浏览器专属
  onDownloadProgress: function (progressEvent) {
    // 处理原生进度事件
  },

  // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
  maxContentLength: 2000,

  // `maxBodyLength`仅Node定义允许的http请求内容的最大字节数
  maxBodyLength: 2000,

  // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
  // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`)
  // 则promise 将会 resolved否则是 rejected。
  validateStatus: function (status) {
    return status >= 200 && status < 300; // 默认值
  },

  // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
  // 如果设置为0则不会进行重定向
  maxRedirects: 5, // 默认值

  // `socketPath` 定义了在node.js中使用的UNIX套接字。
  // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
  // 只能指定 `socketPath` 或 `proxy` 。
  // 若都指定,这使用 `socketPath` 。
  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` 定义了代理服务器的主机名,端口和协议。
  // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
  // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
  // `auth`表示应使用HTTP Basic auth连接到代理并且提供凭据。
  // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
  // 如果代理服务器使用 HTTPS则必须设置 protocol 为`https`
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // see https://axios-http.com/zh/docs/cancellation
  cancelToken: new CancelToken(function (cancel) {
  }),

  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. If set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true // 默认值

}

跨域请求

axios不支持跨域请求可以使用 vue-resource 发送跨域请求

拦截器

在请求或响应被 thencatch 处理前拦截它们。

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    // 例如本地的 token 未过期, 那么在config中添加token
    config.headers.Authorization = `Bearer ${store.getters.token}` // 在请求头添加token
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    // 例如可以在这里添加提示弹窗
    return response;
  }, function (error) {
    // 对响应错误做点什么
    // 例如可以对登录过期的删除旧的登录信息并跳转登录页
    return Promise.reject(error);
  });

大数字处理

JavaScript 能够准确表示的整数范围在-2^53到 2^53之间不含两个端点超过这个范围无法精确表示这个值这使得 JavaScript 不适合进行科学和金融方面的精确计算

//ES6 引入了Number.MAX_SAFE_INTEGER和Number.MIN_SAFE_INTEGER这两个常量用来表示这个范围的上下限
Number.MAX_SAFE_INTEGER === 9007199254740991  // true
Number.MIN_SAFE_INTEGER === -9007199254740991  // true
npm i json-bigint
import axios from 'axios'

import jsonBig from 'json-bigint'

var json = '{ "value" : 9223372036854775807, "v2": 123 }'

console.log(jsonBig.parse(json))

const request = axios.create({
  baseURL: '你接口的基础路径', // 接口基础路径

  // transformResponse 允许自定义原始的响应数据(字符串)
  transformResponse: [function (data) {
    try {
      // 如果转换成功则返回转换的数据结果
      return jsonBig.parse(data)
    } catch (err) {
      // 如果转换失败,则包装为统一数据格式并返回
      return {
        data
      }
    }
  }]
})

export default request
//使用的时候转为字符串来使用。
jsonBig.parse(bigNumber).toString()