Axios package interception

A, axios package

In vue project, and get the data back this interaction, we usually use the axios library, which is based on the promise of http library, you can run in the browser and node.js in. He has a lot of excellent features, such as intercepting requests and responses, cancellation request, convert json, clients and other defense cSRF. So we are also determined to give up much, especially the maintenance of its official repository vue-resource directly recommend we use axios library.

installation

npm install axios; // 安装axios

Introduced

In general I would src directory of the project, request a new folder, and then create a new utils.js a api.js file inside. http.js file is used to package our axios, api.js to our unified management interface.

 

Switching environment

Our project environment may have development, test and production environments. We have to match our default interface url prefixed by the environment variable node.

// 环境的切换
if (process.env.NODE_ENV == 'development') {    
    axios.defaults.baseURL = 'https://www.baidu.com';} else if (process.env.NODE_ENV == 'debug') { axios.defaults.baseURL = 'https://www.ceshi.com'; } else if (process.env.NODE_ENV == 'production') { axios.defaults.baseURL = 'https://www.production.com'; }

Set request timeout

通过axios.defaults.timeout设置默认的请求超时时间。例如超过了10s,就会告知用户当前请求超时,请刷新等。
axios.defaults.timeout = 10000;
 

post request header set

When post requests, we need to add a request headers, so it can be a default setting here, that is set to post the request header  application/x-www-form-urlencoded;charset=UTF-8

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';


Request Interceptor

import Axios from "axios"
import qs from "qs"
let request  = Axios.create();

// add request interceptor
request.interceptors.request.use(function (config) {
    // What to do before sending the request
    
    if(config.method === "post" && !(config.data instanceof FormData)){
    
      config.data = qs.stringify(config.data)
    }
   
    return config;
  }, function (error) {
    // What do request error
    return Promise.reject(error);
  });

// add response interceptor
request.interceptors.response.use(function (response) {
    // do something in response to data
    return response.data;
  }, function (error) {
    // do something wrong response
    return Promise.reject(error);
  });

export default request
 
// where qs conversion requires attention
 

Loading get and post method

 

There are get, post, put and other methods we used ajax request method, we believe that small partners are not unfamiliar. axios corresponding there are many similar approach may look unclear documentation. But in order to simplify our code, we still have to be a simple package. Here we package two main methods: get and post.

get method : we get a function defined by, the get function has two parameters, the first parameter represents the url we want to request the second parameter is a parameter request to be carried our. function returns the object get a promise, when axios successfully resolve it requests the server returns the value, reject the request fails error value. Finally get thrown function through export.

/**
 * get方法,对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params){    
    return new Promise((resolve, reject) =>{ axios.get(url, { params: params }).then(res => { resolve(res.data); }).catch(err =>{ reject(err.data) }) });}
 


Guess you like

Origin www.cnblogs.com/oceanleader/p/12116171.html