Axios基本使用

介绍

Axios 是一个基于promise网络请求库,作用于node.js和浏览器中

特性

  • 从浏览器创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防御XSRF

安装

项目中
bash 复制代码
npm install axios
yarn add axios
学习阶段
html 复制代码
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.min.js"></script>

基本使用

js 复制代码
axios({
    //方法
    method: "",
    //url
    url: "",
    //设置请求体
    //data: {}
}).then(response => {
    console.log(response);
    //...
});

API

axios.request(config)
JS 复制代码
axios.request({
    //方法
    method: "",
    //url
    url: "",
}).then(response => {
    console.log(response);
    //...
});
axios.post(url[, data[, config]])
JS 复制代码
axios.post("http://....", {
    "body":"喜大普奔",
    "postId":2
}).then(response => {
    console.log(response);
    //...
});
其他
JS 复制代码
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

axios返回结果

config:为axios配置项,

data:服务器返回的数据,axios默认做json转换。

headers:http响应头

request: 原生ajax对象

status:状态码

statusText:状态描述

axios 配置对象

这些是用于发出请求的可用配置选项。

JSON 复制代码
{
  url: '/user',
  method: 'get', // default
  baseURL: 'https://some-domain.com/api/',
  //对请求数据做预先处理
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],
  //对响应数据进行预处理
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],
  // 请求头信息配置
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  //发送请求时url后边的参数?id=12345&name=张三
  params: {
  	ID: 12345,
    name:"张三"
  },
  // `paramsSerializer` is an optional config in charge of serializing `params` 一般用的不多
  paramsSerializer: {
    encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashion
    serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized.
    indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes)
  },
  //第一种data形式,对象形式
  data: {
    firstName: 'Fred'
  },
  //第一种data形式,字符串形式
  data:'Country=Brasil&City=Belo Horizonte',
  //请求时间
  timeout: 1000,
  //跨域请求是否把cookie携带过去,false不携带
  withCredentials: false,
  responseType: 'json', // default
  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
  ...
  //代理,一般用在nodejs里面
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },
  ...
}

设置默认配置

JS 复制代码
axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {
    page: 0,
    size: 5
}
axios.defaults.timeout = 3000
axios({
    //url
    url: "/api/getHaoKanVideo"
}).then(response => {
    console.log(response);
});

创建实例对象发送请求

js 复制代码
const a1 = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
const a2 = axios.create({
  baseURL: 'https://api.apiopen.top',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
//发送请求
a1({
    url:"xxxx",
    method:"get"
}).then(response => {
    console.log(response);
})

当需要请求不同域名发送不同请求时可以创建实例对象去发送请求。

下面列出了可用的实例方法。指定的配置将与实例配置合并。

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#getUri([config])

拦截器

拦截器其实是一些函数,可以在请求和响应之前处理数据、权限判断等。

JS 复制代码
//请求拦截器
axios.interceptors.request.use(function (config) {
    //可以对config进行设置
    throw ("error")
    //return config;
}, function (error) {
    return Promise.reject(error);
});

//响应拦截器
axios.interceptors.response.use(function (response) {
    //可以对response进行处理
    return response;
}, function (error) {
    return Promise.reject(error);
});

axios({
    method:"get",
    url: "http://localhost:3300/api/getHaoKanVideo"
}).then(response => {
    console.log(response);
});

如果请求拦截器抛出异常,那么响应拦截器执行use中第二个参数回调方法。

请求拦截器执行顺序与响应拦截器不同:

JS 复制代码
axios.interceptors.request.use(function (config) {
    console.log("请求拦截器-1")
    return config;
}, function (error) {
    return Promise.reject(error);
});
axios.interceptors.request.use(function (config) {
    console.log("请求拦截器-2")
    return config;
}, function (error) {
    return Promise.reject(error);
});

//响应拦截器
axios.interceptors.response.use(function (response) {
    console.log("请求拦截器-1")
    return response;
}, function (error) {
    return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
    console.log("请求拦截器-2")
}, function (error) {
    return Promise.reject(error);
});

axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {
    page: 0,
    size: 5
}
axios({
    //url
    url: "/api/getHaoKanVideo"
}).then(response => {
    console.log("执行结果-3")
    console.log(response);
});

执行的结果为:

请求拦截器后加入的会先执行。

相关推荐
伍哥的传说7 小时前
CSS+JavaScript 禁用浏览器复制功能的几种方法
前端·javascript·css·vue.js·vue·css3·禁用浏览器复制
lichenyang4537 小时前
Axios封装以及添加拦截器
前端·javascript·react.js·typescript
Trust yourself2438 小时前
在easyui中如何设置自带的弹窗,有输入框
前端·javascript·easyui
Feather_749 小时前
从Taro的Dialog.open出发,学习远程控制组件之【事件驱动】
javascript·学习·taro
波波鱼દ ᵕ̈ ૩10 小时前
学习:JS[6]环境对象+回调函数+事件流+事件委托+其他事件+元素尺寸位置
前端·javascript·学习
cypking11 小时前
解决electron+vue-router在history模式下打包后首页空白问题
javascript·vue.js·electron
Watermelo61711 小时前
极致的灵活度满足工程美学:用Vue Flow绘制一个完美流程图
前端·javascript·vue.js·数据挖掘·数据分析·流程图·数据可视化
Micro麦可乐11 小时前
前端拖拽排序实现详解:从原理到实践 - 附完整代码
前端·javascript·html5·拖拽排序·drop api·拖拽api
Watermelo61711 小时前
Web Worker:让前端飞起来的隐形引擎
前端·javascript·vue.js·数据挖掘·数据分析·node.js·es6