Axios Package (i) basic configuration

Source: Internet
Author: User

axiosIs the current popular Promise Network Request library, in the browser side he xhr created Ajax requests by way. In the node environment, http create a network request through the library.

axiosProvides a rich set of configurations, here is the basic configuration method I usually use in my work.

Because I am working vue with development, the following code defaults to the environment vue-cli .

Create a Axios instance

Why create an instance instead of axios axios configuring it on an object? Because we are dealing with complex usage scenarios, and multiple instances are easy to manage.

ConstIsdev= Process.Env.node_env === ' development ';ConstInstance= Axios.Create({  //BaseURL is a configuration that will be forwarded in proxytable, and can be requested using different URLs in the development and production environment, judging by the environment variables  BaseURL:Isdev? '/fakeapi ':'/api ',  Timeout:  the,  Validatestatus(status){    //In general, when HTTP status is between 200-300, it is determined that the request passed, you can modify this configuration here (not recommended modification)    returnStatus===  $  },  Headers: {    //define POST request encoding format    Post: {      ' Content-type ': ' Application/x-www-form-urlencoded;charset=utf-8 '    }  }});
Processing Request Parameters

Although the requested encoding format, but still need to further set the specific encoding format, such as I want to make some special settings.

qs.stringifyPlease refer to this article for the parameters here Qs.js-Better handling URL parameters

ImportQs from ' QS ';instance.Interceptors.Request. Use(config= {    //You can also add a field such as token to the request here    Config.Data = Qs.stringify(Config.Data, {Arrayformat: ' Repeat ', Allowdots: true});    returnConfig;},Err= {    return Promise.Reject(ERR);});
Handling Return Values
importfrom‘./httpErrorHandler.js‘;instance.interceptors.response.use(function{    // 这里可以对返回数据进行处理,比如验证code是否为1等    returndata.data;}, httpErrorHandler)

httpErrorHandler.jsCode

# httpErrorHandler.jsexport default (error) => {  if (!error.response) {    return Promise.reject({        msg: ‘网络连接超时‘,        error    });  };  let msg = ‘‘;  const status = error.response.status;  switch (status) {    case 400:        msg = ‘错误的请求参数‘;        break;    case 401:        msg = ‘没有该操作权限‘;        break;    case 403:        msg = ‘请登录‘;        break;    case 404:        msg = ‘错误的请求地址‘;        break;    case 500:    case 501:    case 502:    case 503:    case 504:        msg = ‘服务器错误‘;        break;    default:        msg = ‘未知错误‘ + status;  }  return Promise.reject({      msg,      error  });}
Encapsulating the Get method

and jquery.ajax different, axios get methods need to prarms pass through instead of data parameters:

/*** Post-packaged Axios get method * * @param {string}URL Request Path * @param {Object}option Request Parameter * @param {Object}[Config] special configuration item (optional) * @returns */Export function Get(URL,Option,Config= {}){  return instance.Get(URL, { params:Option},Config}//Call GetGet(' http://baidu.com ', {    a: 1,    b: 2}). Then(...).Catch(...)
Post mode

The Post request method is simpler and does not require the use of prarms parameters

/*** Axios Post method after encapsulation * * @param {string}URL Request Path * @param {Object}option Request Parameter * @param {Object}[Config] special configuration item (optional) * @returns */Export function Get(URL,Option,Config= {}){  return instance.Get(URL,Option,Config}//Call postPost(' http://baidu.com ', {    a: 1,    b: 2}). Then(...).Catch(...)
Upload file

Uploading a file requires a different header setting and encoding, so you need to create a separate instance

ConstUploadinstance= Axios.Create({  BaseURL:Isdev? '/fakeapi ':'/api ',  Timeout: 15000,  Headers: {    //Send file the required encoding format    ' Content-type ': ' Multipart/form-data '  }});/*** Axios Upload method after encapsulation * * @param {string}URL Request Path * @param {Formdata}formdata request parameter, must be Formdata object * @param {Object}[Config] special configuration item (optional) * @returns */Export function Upload(URL,Formdata,Config= {}){  return uploadinstance.Post(URL,Formdata,Config}# Use Upload LetFormData= New FormData();FormData.Append("Image",File;FormData.Append("Name", ' name ');Upload(' http://baidu.com ',FormData, {    onuploadprogress(progressevent){        //Display upload progress, etc.    }})

Axios Package (i) basic configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.