Front-end interview questions, vue detailed explanation (axios)

Today, we will carefully talk about axios in terms of how to use axios and the concept of axios.

1. Install and use axios

npm install

 npm install axios --save

Introduced through cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Create new http.js, encapsulate get and post requests of axios

import Axios from 'axios'
import ElementUI from 'element-ui' 
const get = (url, params, config) => {
  // url为我们接口的地址
  url = '/api/' + url //本地开发环境
  return new Promise((resolve, reject) => {
    Axios.get(url, params, config)
      .then(res => {
        resolve(res.data)
        if (res.data.code && res.data.code != 0) {
          ElementUI.Message.error(res.data.message || res.message || '系统错误')
        }
      })
      .catch(err => {
        reject(err)                 
      })
  })
}
const post = (url, params, config) => {
  // url为我们接口的地址
  url = '/api/' + url //本地开发环境 
  return new Promise((resolve, reject) => {
    Axios.post(url, params, config)
      .then(res => {
        resolve(res.data)
        if (res.data.code && res.data.code != 0) {
          ElementUI.Message.error(res.data.message || res.message || '系统错误')
        }
      })
      .catch(err => {
        reject(err)          
      })
  })
}
export default {
  get,
  post
}

New request interception AxiosPlugin.js, encapsulating the request interceptor

import axios from 'axios'
import router from '../router.js'

// 创建 axios 实例
export const Axios = axios.create({
  timeout: 15000
})

window.cancelInterface = []
//POST传参序列化(添加请求拦截器)
// 在发送请求之前做某件事
axios.interceptors.request.use(
  config => {
    config.cancelToken = new axios.CancelToken(cancel => {
      if (!window.cancelInterface) {
        window.cancelInterface = []
      }
      window.cancelInterface.push({
        cancel
      })
    })
    // console.log('config.token', config)
    if (config.token != 'none') {
      if (localStorage.token) {
        config.headers.Authorization = 'Bearer ' + localStorage.token
      }
    }

    return config
  },
  error => { 
    return Promise.reject(error)
  }
)

//返回状态判断(添加响应拦截器)
axios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8'
axios.interceptors.response.use(
  res => {
    if (res.data.code == '401') {
      router.push({
        path: '/login',
        query: {
          redirect: location.hostname
        }
      })
      return
    }
    //503跳转到错误页
    if (res.data.code == '503') {
      router.push({
        path: '/error',
        query: {
          redirect: location.hostname
        }
      })
      return
    }
    return res
  },
  error => {
    if (error.response.status === 401 || error.response.status === 403) {
      router.push({
        path: '/login',
        query: {
          redirect: location.hostname
        }
      })
    } else if (error.response.status === 503 ) {
      //503跳转到错误页
      router.push({
        path: '/error',
        query: {
          redirect: location.hostname
        }
      })
    } else if (error.response.status === 500) {
      // 服务器错误
      return Promise.reject(error.response.data)
    } 
    // 返回 response 里的错误信息
    return Promise.reject(error.response.data)
  }
)
// 将 Axios 实例添加到Vue的原型对象上
export default {
  install(Vue) {
    Object.defineProperty(Vue.prototype, '$http', {
      value: Axios
    })
  }
}

2. What is axios?

  1. Axios is a promise-based HTTP library that can be used in browsers and node.js. The most popular ajax request library on the front end,
  2. React / vue officially recommends using axios to send ajax requests

3. The characteristics of axios?

  1. Asynchronous ajax request library based on promise, supporting all APIs of promise
  2. Both browser and node can be used, XMLHttpRequests are created in the browser
  3. Support request / response interceptor
  4. Support request cancellation
  5. Can convert request data and response data, and automatically convert the returned content into JSON type data
  6. Send multiple requests in batch
  7. The security is higher, and the client supports defense against XSRF, which means that each of your requests carries a key obtained from the cookie. According to the browser's homology policy, the fake website cannot get the key from your cookie. In this way, the background can easily distinguish whether the request is a user's misleading input on the fake website, so as to adopt the correct strategy.

4. What are the common syntax of axios?

axios(config): 通用/最本质的发任意类型请求的方式
axios(url[, config]): 可以只指定 url 发 get 请求
axios.request(config): 等同于 axios(config)
axios.get(url[, config]):get 请求
axios.delete(url[, config]):delete 请求
axios.post(url[, data, config]): 发 post 请求
axios.put(url[, data, config]): 发 put 请求
axios.defaults.xxx: 请求的默认全局配置
axios.interceptors.request.use(): 添加请求拦截器
axios.interceptors.response.use(): 添加响应拦截器
axios.create([config]): 创建一个新的 axios(它没有下面的功能)
axios.Cancel(): 用于创建取消请求的错误对象
axios.CancelToken(): 用于创建取消请求的 token 对象
axios.isCancel(): 是否是一个取消请求的错误
axios.all(promises): 用于批量执行多个异步请求
axios.spread(): 用来指定接收所有成功数据的回调函数的方法

5. Why can axios run both in the browser environment and the server (node) environment?

axios uses the XMLHttpRequest object to send ajax requests in the browser; the http object is used to send ajax requests in the node environment.

var defaults.adapter = getDefaultAdapter();
function getDefaultAdapter () {
	var adapter;
    if (typeof XMLHttpRequest !== 'undefined') {
    	// 浏览器环境
        adapter = require('./adapter/xhr');
    } else if (typeof process !== 'undefined') {
    	// node环境
        adapter = require('./adapter/http');
    }
   return adapter;
}

The above lines of code can be seen: XMLHttpRequest is an API, which provides the client with the function of transferring data between the client and the server; the process object is a global (global variable) that provides relevant information and controls the current Node. js process. The original author judges the running environment of the program by judging the two global variables XMLHttpRequest and process, so as to provide different http request modules in different environments to achieve compatibility between the client and server programs.

6. Why use axios without native ajax?

Because ajax has the following shortcomings compared to axios:
1. It is programming for MVC, which does not meet the current wave of front-end MVVM.
2. Based on the native XHR development, the architecture of XHR itself is not clear.
3. The entire JQuery project is too large, and it is very unreasonable to use the entire JQuery simply by using ajax (taking a personalized packaging solution and not being able to enjoy the CDN service)
4. Does not meet the principle of separation of concerns
5. Configuration and The calling method is very confusing, and the asynchronous model based on events is not friendly.

Published 30 original articles · praised 34 · 20,000+ views

Guess you like

Origin blog.csdn.net/weixin_41698051/article/details/105557611