【uniapp公衆號分銷商城從0到1】數據請求封裝帶攔截器(01)

interface.js

/**
 * 通用網絡請求
 * 基於 Promise 對象實現更簡單的 request 使用方式,支持請求和響應攔截
 */

export default {
	config: {
		baseUrl: "https:",
		header: {
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},  
		data: {},
		method: "GET",
		dataType: "json",  /* 如設爲json,會對返回的數據做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		//TODO 加密數據
		
		//TODO 數據簽名
		/* 
		_token = {'token': getStorage(STOREKEY_LOGIN).token || 'undefined'},
		_sign = {'sign': sign(JSON.stringify(options.data))}
		options.header = Object.assign({}, options.header, _token,_sign) 
		*/
	   
		return new Promise((resolve, reject) => {
			let _config = null
			
			options.complete = (response) => {
				let statusCode = response.statusCode
				response.config = _config
				if (process.env.NODE_ENV === 'development') {
					if (statusCode === 200) {
						console.log("【" + _config.requestId + "】 結果:" + JSON.stringify(response.data))
					}
				}
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				// 統一的響應日誌記錄
				_reslog(response)
				if (statusCode === 200) { //成功
					resolve(response);
				} else {
					reject(response)
				}
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			
			// 統一的請求日誌記錄
			_reqlog(_config)

			if (process.env.NODE_ENV === 'development') {
				console.log("【" + _config.requestId + "】 地址:" + _config.url)
				if (_config.data) {
					console.log("【" + _config.requestId + "】 參數:" + JSON.stringify(_config.data))
				}
			}

			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'  
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}


/**
 * 請求接口日誌記錄
 */
function _reqlog(req) {
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + req.requestId + "】 地址:" + req.url)
		if (req.data) {
			console.log("【" + req.requestId + "】 請求參數:" + JSON.stringify(req.data))
		}
	}
	//TODO 調接口異步寫入日誌數據庫
}

/**
 * 響應接口日誌記錄
 */
function _reslog(res) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + res.config.requestId + "】 地址:" + res.config.url)
		if (res.config.data) {
			console.log("【" + res.config.requestId + "】 請求參數:" + JSON.stringify(res.config.data))
		}
		console.log("【" + res.config.requestId + "】 響應結果:" + JSON.stringify(res))
	}
	//TODO 除了接口服務錯誤外,其他日誌調接口異步寫入日誌數據庫
	switch(_statusCode){
		case 200:
			break;
		case 401:
			break;
		case 404:
			break;
		default:
			break;
	}
}

 index.js

所有的接口都在這裏設置【寫了一個模板可以照抄】

import http from './interface'

const baseUrl = "";
// const baseUrl = "";
// const baseUrlsms = "";
const baseUrlsms = "";
const baseUrlUat = "";
const mapBaseUrl = "https://restapi.amap.com";
const wxUrl = "https://open.weixin.qq.com";



export const getUserCouponList = (data) => {
	http.config.baseUrl = baseUrl;
	//設置請求前攔截器
	http.interceptor.request = (config) => {
		config.header = {
			"token": uni.getStorageSync('token')
		}
	}
	//設置請求結束後攔截器
	http.interceptor.response = (response) => {
		return response;
	}
    return http.request({
		baseUrl: baseUrl,
        url: 'getUserCouponList', 
        method: 'GET', 
        data,
		// handle:true 
    })
}
// 默認全部導出  import api from '@/common/vmeitime-http/'
export default {
	getUserCouponList
}

main.js

import Vue from 'vue'
import App from './App'
import api from '@/common/vmeitime-http/'
import cx from './common/canvas_x'//這個是生成海報的一個js先不管她

Vue.config.productionTip = false

Vue.prototype.$api = api

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()

 

【有時間持續更新中~】

發佈了106 篇原創文章 · 獲贊 17 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章