当前位置:   article > 正文

前端热门技术axios详细讲解(一)——基本使用方法_前端axios的使用

前端axios的使用

前言:
axios 作为前端必学技术,它实质上是一个基于XMLHttpRequestpromise 的 HTTP 库,VueReact都推荐使用它发送ajax请求。
本文主要讲述axios发送请求时要掌握的知识点。

一、axios的特点

  • 在浏览器和node中都可以使用
  • 支持 Promise API
  • 可以拦截请求、响应
  • 转换请求数据、响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

传送门:点击这里到github

二、使用方法

在项目中安装:

$ npm install axios
  • 1

$ yarn add axios
  • 1

使用cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • 1
1. 默认配置

我们可以给axios设置一个默认的基本配置,里面包括 url、method 等,设置好之后就不用每次添加了。(只有 url 是必需的,如果没有指定 method,请求将默认使用 get 方法。)

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';
  • 1
  • 2
  • 3
2. 自定义全局配置
// 设置配置对象
const configOptions={
  baseURL: 'https://api.example.com',
  timeout:30000, // 超时取消请求
  withCredentials: true, // 表示跨域请求时是否需要使用凭证,默认false
}
//创建实例时,传入配置
const instance = axios.create(configOptions);

// 实例创建后更改默认值
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

注意:配置是有优先级的,这个顺序是:在 lib/defaults.js 找到的库的默认值 < 是实例的 defaults 属性 < 请求的 config 参数。后者将优先于前者。

3. 请求配置
{
   // `url` 是用于请求的服务器 URL
  url: '/user',
  // `method` 是创建请求时使用的方法
  method: 'get', // default
  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',
  /* `transformRequest`:向服务器发送前,修改请求数据;
 	只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法;
  后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream */
  transformRequest: [function (data, headers) {
    // 对 data 进行任意转换处理
    return data;
  }],
  // `transformResponse` 在传递给 then/catch 前,修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

官方为了方便起见,给axios的常用方法专门起了别名,可以直接像这样使用:axios.get(),axios.post(),axois.put()等等。如图:
axios的请求方法

这里只介绍基本的,更多详细内容请点击这里

4. 发送get请求

get 请求传参可以直接加在地址后,或写在params对象中。

const axios = require('axios').default;
// 第一种:直接加在地址后,用问号?传参
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// 第二种:在花括号中用params对象传参
axios.get('/user', {
    params: {
      ID: 12345
    }
  })  
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
5. 发送post请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/784024
推荐阅读
相关标签
  

闽ICP备14008679号