Use the Axios package as a Vue plugin

Source: Internet
Author: User

Objective

Since Vue2.0 recommended that everyone use Axios to start, Axios is more and more people understand. Using Axios to initiate a request is a relatively simple thing for everyone, but Axios has no encapsulation reuse, and the project is getting bigger and larger, resulting in code redundancy. It will be a very troublesome thing. So this article will show you in detail how to encapsulate the request and reuse it in the project component. A friend in need can do a reference.

Basic Requirements for encapsulation
    • Unified URL Configuration
    • Unified API Requests
    • request blocker, e.g. with token, set request header
    • Response (response) interceptors, such as: Unified error handling, page redirection, etc.
    • As needed, combine Vuex to do global loading animations, or error handling
    • Encapsulate the Axios into a Vue plug-in using
File structure

Create a new HTTP folder under the SRC directory

Default configuration for config.js Axios
api.js Two-time package Axios, interceptors, etc.
interface.js Request Interface file
index.js encapsulating Axios as a plug-in

Config.js

Please refer to Axios's official documentation for full configuration

export default {  method: ‘get‘,  // 基础url前缀  baseURL: ‘https://www.example.com/api‘, // 请求头信息 headers: { ‘Content-Type‘: ‘application/json;charset=UTF-8‘ }, // 参数 data: {}, // 设置超时时间 timeout: 10000, // 携带凭证 withCredentials: true, // 返回数据类型 responseType: ‘json‘}
Api.js
Import AxiosFrom' Axios ';Import ConfigFrom'./config ';Import QSFrom' Qs ';Import CookiesFrom"Js-cookie";Import RouterFrom' @/router 'Use Vuex when doing global loadingImport store from ' @/store 'ExportDefaultfunction$axios (Options) {ReturnNewPromise (Resolve, reject) = {Const Instance = axios.create ({baseURL:config.baseURL, headers: {}, Transformresponse: [function (Data) {}]})Request Interceptor Instance.interceptors.request.use (config + = {Let token = Cookies.get (' MarkToken ')1. When the request starts, you can combine Vuex to open the full-screen loading animationConsole.log (store.state.loading)Console.log (' Prepare to send request ... ')2. Take token.if (token) {Config.headers.accessToken = token}else {Redirect to login page Router.push ('/login ')}3. According to the request method, serialize the transmitted parameters according to whether the backend requirements are serializedif (Config.method = = =' Post ') {if (config.data.__proto__ = = = Formdata.prototype | | config.url.endsWith (' Path ') | | Config.url.endsWith (' Mark ') | | Config.url.endsWith (' Patchs ')) {}else {config.data = Qs.stringify (Config.data)}}return config}, error = {When the request is wrongConsole.log (' Request: ', error)1. To determine the request timeoutif (Error.code = = =' Econnaborted ' && error.message.indexOf (' Timeout ')!==-1) {Console.log (' Timeout request timed out ')Return Service.request (originalrequest);//repeat request once}2. Need to redirect to error pageConst ERRORINFO = Error.responseConsole.log (errorinfo)if (errorinfo) {Error =errorinfo.data//page The catch at the time you can get the detailed information, see the bottom of the Promise.rejectConst ERRORSTATUS = errorinfo.status;404 403 ... router.push ({path:'/error/${errorstatus})}ReturnPromise.reject (Error)You can get (catch) The error message you want to return on the other side of the call})Response Interceptor Instance.interceptors.response.use (response = {let data;IE9 Response.data is undefined, so you need to use Response.request.responseText (the string after stringify)if (Response.data = =Undefined) {data =Json.parse (Response.request.responseText)}else {data = Response.data}Different processing according to the code value returnedSwitch (data.rc) {Case1:Console.log (DATA.DESC)BreakCase0:store.commit (' Changestate ')Console.log (' Login successful ')Default:}Throws an error if it is not correctly returned code and is already logged inConst ERR = new Error (DATA.DESC)Err.data = DataErr.response = responseThrow errReturn Data}, err + = {if (Err && err.response) {Switch (err.response.status) {Case400:err.message =' Request error 'BreakCase401:err.message =' Not authorized, please login 'BreakCase403:err.message =' Access Denied 'BreakCase404:err.message =' Request address error:${err.response.config.url} 'BreakCase408:err.message =' Request timed out 'BreakCase500:err.message =' Server Internal error 'BreakCase501:err.message =' Service not implemented 'BreakCase502:err.message =' Gateway error 'Breakcase 503:err.message =  ' Service Unavailable ' Span class= "Hljs-keyword" >break case 504:err.message =  "Gateway Timeout ' break case 505:err.message =  ' HTTP version not supported '  Break default:}} console.error (ERR) return promise.reject (err) // Returns the error message returned by the interface}) //request processing instance (options). Then (res = {Resolve (res) return false}). catch (Error = = {reject (Error)})})}    
Interface.js
Import AxiosFrom'./api '/* Unify all interfaces for easy maintenance * If the project is large you can separate the URL into a file, the interface is divided into different modules *///separate export export const query = () = > {return axios ({url:  '/query ', Method: " Get '})} export const list = (id) + = {return axios ({url:  '/list${id} ', Method: Span class= "hljs-string" > ' Get '})}export const upload = data = > {return axios ({url:  '/upload ', Method:  ' post ', data}"}//default all Export export default {query, list, upload}           
Index.js

Package into Vue plugin

// 导入所有接口import apiList from ‘./interface‘const install = Vue => { if (install.installed) return; install.installed = true; Object.defineProperties(Vue.prototype, { // 注意哦,此处挂载在 Vue 原型的 $api 对象上 $api: { get() { return apiList } } })}export default install
Use

At this end, everything is ready for use, do the following in Mian.js:

import api from ‘./http/index‘Vue.use(api)// 此时可以直接在 Vue 原型上调用 $api 了

Use in Vue

// List.vue...this.$api.list(id).then(res => {     if (res.rc === 0) {          this.pageList = res.data.item      } else { this.$Message.info(res.desc); } }) .catch(error => { this.$Message.info(error); })...
Summarize
    • More than two times the package is more comprehensive, basically completed our previous requirements
    • In the case of error processing, it is also necessary to return the value of the back-end contract to make a specific contract.

This article was published synchronously in https://www.cssge.com

This article is reproduced from the original text front-end link: https://www.cnblogs.com/zhouyangla/p/6753673.html

Use the Axios package as a Vue plugin

Related Article

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.