Based on the axios encapsulation fetch method and call instance, the axios encapsulation fetch instance

Source: Internet
Author: User

Based on the axios encapsulation fetch method and call instance, the axios encapsulation fetch instance

For basic axios usage, see the official axios website.

// Dependent on axios to modify private ajax import Qs from 'qs' import axios from 'axios 'import router from 'router/Index' import {errorPrompt, loading, closeLoading} from 'util/util 'export const status = {SUCCESS: '000000', NET_ERR: '000000', // the network connection is abnormal. Please try BIZ_ERR: '000000' later ', // business request exception NO_AUTH: '000000'} export function fetch (options) {return new Promise (resolve, reject) =>{ let instance = axios. create ({baseURL: process. env. BASE _ API, timeout: 2000, headers: {// "tracecode": window. encodeURIComponent (JSON. stringify ({"ua": "", "cv": "20161230", "token": "3dwo0onUUsPKVJcP8tk", "OS": "windows10", "app ": "kind", "ws": "1*1", "pkey": "f8caf7d7-a5d4-4710-b06f-28a922b6a467"}) "tracecode": commonBizHeader (isManager (options )), 'content-type': 'application/x-www-form-urlencoded'}, transformRequest: [function (data) {// Do whatever you want To transform the data let ret = ''for (let it in data) {ret + = encodeURIComponent (it) + '=' + encodeURIComponent (data [it]) + '&'} return ret}]}); instance. interceptors. request. use (function (response) {// Request Interception loading (); return response ;}, function (error) {console. log ('error Request Interception: ', error) return Promise. reject (error) ;}); instance (options ). then (response => {const res = response. data; If (res. errorCode! = Status. SUCCESS) {switch (res. errorCode) {case status. NET_ERR: {errorPrompt (res. errorMsg) reject (res) break;} case status. BIZ_ERR: {errorPrompt (res. errorMsg) reject (res) break;} case status. NO_AUTH: {errorPrompt (res. errorMsg) let session = require ("storejs") if (isManager (options) {// management session. remove ("managerUserToken") router. push ({path: '/manager/login'})} else {session. remove ("cli EntUserToken ") router. push ({path: '/client/login'})} reject (res) break }}closeloading (); resolve (res );}). catch (error => {closeLoading (); errorPrompt ('network connection error, please check your Network') console. log ('error', error); // for debug reject (error) ;});} function commonBizHeader (isManager) {let session = require ("storejs"); let params = {} params ['ua '] = window. navigator. userAgent. toLowerCase () params ['cv '] =' 123456 'params ['done'] = window. screen. height + '*' + window. screen. width params ['Token'] = "123456" params ['OS'] = window. navigator. appCodeName if (isManager) {params ['Token'] = session. get ('managerusertoken') // manage-User token} else {params ['Token'] = session. get ('clientusertoken') // user-User Token} params ['app'] = 'kind' let UUID = session. get ('pkey') if (! UUID) {UUID = getUUID () window. localStorage. setItem ('pkey', UUID)} return encodeURIComponent (JSON. stringify (params)} function isManager (options) {return options & options. url & options. url. indexOf ("/api/worker ")! =-1}/*** get UUID * @ returns {string} */export function getUUID () {let len = 32 // 32 length let radix = 16 // hexadecimal let chars = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz '. split ('') let uuid = [] let I radix = radix | chars. length if (len) {for (I = 0; I <len; I ++) {uuid [I] = chars [0 | Math. random () * radix]} else {var r uuid [8] = uuid [13] = uuid [18] = uuid [23] = '-'uuid [1 4] = '4' for (I = 0; I <36; I ++) {if (! Uuid [I]) {r = 0 | Math. random () * 16 uuid [I] = chars [(I = 19 )? (R & 0x3) | 0x8: r] }}return uuid. join (''). toLowerCase ()}

This is in the vue project: The Calling method in the api is as follows (react is just getting started and is still doing a simple demo)

import {fetch} from 'api/fetch'export const callAuthCode = (userPhone) => { return fetch({ url: '/api/auth/code', method: 'post', data: ({  userPhone: userPhone, }), })}

Because the background requirements on our side strictly distinguish get/post requests, the encapsulated method call must contain a method. If the background has been processed, all the post requests can be performed, you can refer to the official axios website to change all the methods. post

Description of the fetch method: It mainly encapsulates Request Interception and response interception. By default, the request body is converted from the json format to the form format. Of course, these can be found on the axios official website, it's just a collection.

Do not apply the request header directly. This is a special configuration that is required in the background. The backend interfaces are shared by three terminals and must be distinguished by where the request is called.

The above section shares all the content of the fetch method and call instance based on the axios encapsulation. I hope you can give us a reference and support the customer's house.

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.