您好,登錄后才能下訂單哦!
基礎axios用法請看axios官網
//依賴于axios對私有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: '100', NET_ERR: '101', // 網絡連接異常,請稍候再試 BIZ_ERR: '103', // 業務請求異常 NO_AUTH: '104' } 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) { // 請求攔截 loading(); return response; }, function (error) { console.log('error 請求攔截 : ', 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)) { // 管理端 session.remove("managerUserToken") router.push({path: '/manager/login'}) } else { session.remove("clientUserToken") router.push({path: '/client/login'}) } reject(res) break } } } closeLoading(); resolve(res); }).catch(error => { closeLoading(); errorPrompt('網絡連接錯誤,請檢查您的網絡') 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['ws'] = window.screen.height + '*' + window.screen.width params['token'] = "123456" params['os'] = window.navigator.appCodeName if (isManager) { params['token'] = session.get('managerUserToken') // 管理 - 用戶令牌 } else { params['token'] = session.get('clientUserToken') // 用戶 - 用戶令牌 } 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 } /** * 獲取UUID * @returns {string} */ export function getUUID() { let len = 32 // 32長度 let radix = 16 // 16進制 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[14] = '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() }
這是在vue的項目中:在api中調用方法如下(react剛開始學,還在做簡單demo)
import {fetch} from 'api/fetch' export const callAuthCode = (userPhone) => { return fetch({ url: '/api/auth/code', method: 'post', data: ({ userPhone: userPhone, }), }) }
因為我們這邊的后臺要求嚴格區分get/post請求,所以封裝的方法調用中必須帶有method,如后臺已經處理好,全部可進行post請求,則可以參照axios官網里面將方法全部改為.post
關于fetch方法的說明:主要進行封裝了請求攔截,響應攔截,默認請求體由json格式轉換form格式,當然,這些都是在axios官網里可以找到的,不過是集合下了而已
關于請求頭部分請不要直接套用,這是我們這邊后臺要求特殊配置的,后臺接口三端共用,必須區分是哪里在調用
以上這篇基于axios封裝fetch方法及調用實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。