Introduction to axios and its use in projects

Table of contents

What is axios?

What are the characteristics of axios?

axios common syntax

axios.create(config)

Secondary encapsulation of axios in Vue project

What is axios?

is a promise-based network request library, available in node.js and the browser. Use the native node.js.http module on the server side and XMLHttpRequests on the client side (ie browser side).

Because it is a promise-based request library, it supports the promise API,

       let p = this.$axios.get('/api/just_test');
       console.log(p); // 1 Promise : PromiseStatus = pending
 
        p.then(res=>{   
          console.tiemEnd('x');//5001ms
          console.log(p);// 3 Promise : PromiseStatus = resolved
        });
        p.catch(err=>{
          console.log(p); // 4 Promise : PromiseStatus = reject
        });
 
       console.log('AAAA'); // 2
        
        //输出顺序 1 -> 2 -> 3或4     


       // 后台部分
       def just_test(request):
       time.sleep(5)
       return JsonResponse({'info': 'okok'})   

let p = this.$axios.get('/api/just_test') is equivalent to:

return new Promise( (resolved,reject)=>{         // Call the http library to request data }) // That is, a Promise object is obtained. Note that this is a synchronous call, and the callback function is an asynchronous call. It can be seen that the time is set to stop for 5 seconds in the background, which is used to simulate that it takes 5 seconds to obtain the data. At this time, the status of the promise object is pending, that is, it has not been completed or failed; after 5 seconds, the requested data is completed . , then callback is added to the queue for execution;


 

Axios request returns a promise object, which is consistent with the API in promise, can be chained, and supports async and await 

What are the characteristics of axios?

  1. Axios is a promise-based HTTP library that supports all promise APIs
  2. It can intercept requests and responses, supports request/response interceptors
  3. Support Request Cancellation
  4. It can convert request data and response data, and automatically convert the response content into JSON type data
  5. Batch multiple requests
  6. Higher security, the client supports defense against XSRF

Axios common syntax

axios(config): the general / most essential way to send any type of request
axios(url[, config]): You can only specify the url to send a get request
axios.request(config): equivalent to axios(config)
axios.get(url[, config]): send a get request
axios.delete(url[, config]): send delete request
axios.post(url[, data, config]): send a post request
axios.put(url[, data, config]): send a put request
axios.defaults.xxx: The default global configuration requested
axios.interceptors.request.use(): Add request interceptor
axios.interceptors.response.use(): add response interceptor
axios.create([config]): Create a new axios ( it does not have the following functions )
axios.Cancel(): Error object used to create a cancellation request
axios.CancelToken(): A token object used to create a cancellation request
axios.isCancel(): Is it an error to cancel the request
axios.all(promises): Used to execute multiple asynchronous requests in batches
axios.spread(): The method used to specify the callback function that receives all successful data

axios.create(config)

1. Create a new axios according to the specified configuration, that is, each new axios has its own configuration
2. The new axios just doesn't have a method to cancel the request and send the request in batches , and all other syntaxes are consistent
3. Why is this grammar designed ?
(1) Requirements : The configuration required by some interfaces in the project is not the same as that required by other interfaces
how to deal with
(2) Solution : Create 2 new axios, each with its own unique configuration , which are applied to different requirements
In request interface request

Secondary encapsulation of axios in Vue project

// 对于axios进行二次封装,加上了请求和响应拦截器
import axios from 'axios'
// 引入进度条
import nprogress from 'nprogress'
// start进度条开始,done进度条结束
//引入进度条的样式
import 'nprogress/nprogress.css'
// 在当前模块中引入 store
import store from '@/store'

// 1.利用axios对象的方法create,去创建一个axios实例
// 2. requests就是axios
const requests = axios.create({
    // 配置对象
    // 基础路径,发送请求的时候,所有路径中都加上/api
    baseURL:'/api',
    //代表请求超时的时间
    timeout:5000,
})

// 请求拦截器,在发送请求之前做一些事情
requests.interceptors.request.use((config)=>{
    // config: 配置对象,对象里面有一个属性很重要,即 header请求头
    if(store.state.detail.uuid_token){
        // 给请求头添加一个字段(userTempId):和后端协商一致 表明用户临时身份
        config.headers.userTempId = store.state.detail.uuid_token;
    }
    // 需要携带token给服务器  验证用户身份 在使用游客身份加入购物车的时候使用
    if(store.state.user.token){
        config.headers.token = store.state.user.token;
    }
    // 发请求之前 进度条开始动
    nprogress.start();
    return config
})

// 响应拦截器
requests.interceptors.response.use((response)=>{ 
    // 成功的回调函数: 服务器相应数据回来以后,响应拦截器可以检测到,可以做一些事情

   //  请求成功以后能够拿到相应的数据以后,使进度条结束
    nprogress.done()
   return response.data;
},(error)=>{
    // 响应失败的回调函数
    return Promise.reject(new Error('failed'))
})


// 对外暴露
export default requests


 

Guess you like

Origin blog.csdn.net/csdssdn/article/details/126159492