vue开发uniapp接口封装

vue开发uniapp接口封装

1. 创建api文件夹
2. 创建3个js,api.js, conom.js, http.js
3. api.js内容

const baseUrl = "https://stage.ocheng.me/api/";
const Channel=68

const requestBase = {
	baseUrl: baseUrl, // 此为测试地址,需加入到域名白名单,或者更改为您自己的线上地址即可
	dataType: 'json', // 可删除,默认为json
	responseType: 'text', // 可删除,默认为text
	// 设置请求头,支持所有请求头设置,也可不设置,去掉header就行
	header: {
		Accept: 'application/json',
		'Content-Type': 'application/json',
		'X-Channel': Channel,
		'X-Channel-Type': 1,
		'X-Security-Feign': 'true'
		
	}
}
export default {
	baseUrl,
	requestBase,
	Channel,
}

4. conom.js内容 请求方式的种类和判断

import requestBase from './api.js'


class Request {
	constructor() {
		let config = requestBase.requestBase
		this.config = config
		// this.config.baseUrl = config.baseUrl? config.baseUrl: '';
		// this.config.dataType = config.dataType? config.dataType: 'json';
		// this.config.responseType = config.responseType? config.responseType: 'text';
		this.config.header = config.header ? config.header : {};
		this.reqInterceptors = null
		this.resInterceptors = null
		this.interceptors = {
			request: fn => {
				this.reqInterceptors = fn
			},
			response: fn => {
				this.resInterceptors = fn
			}
		}
	}
	async get(url, config = {}) {
		return this._request('get', url, config)
	}
	async post(url, config = {}) {
		return this._request('post', url, config)
	}
	async put(url, config = {}) {
		return this._request('put', url, config)
	}
	async delete(url, config = {}) {
		return this._request('delete', url, config)
	}
	setConfig(config = {}) {
		this.config = this._deepCopy(this._merge(this.config, config))
	}
	getConfig() {
		return this.config
	}
	_request(method, url, config) {
		uni.showLoading({
			title:'加载中...',
		});
		const _this = this
		let newConfig = {..._this.config}
		// let newConfig = this._deepCopy(this._merge(this.config, config))
		let lastConfig = {
			data: config ? config : {},
			header: newConfig.header,
			dataType: newConfig.dataType,
			responseType: newConfig.responseType,
			baseUrl:newConfig.baseUrl
		}
		let fullUrl = _this._formatUrl(lastConfig.baseUrl, url)
		return new Promise((resolve, reject) => {
			uni.request({
				url: fullUrl,
				method,
				data: lastConfig.data,
				header: lastConfig.header,
				dataType: lastConfig.dataType,
				responseType: lastConfig.responseType,
				async complete(response) {
					uni.hideLoading();
					let res = response
					if (
						_this.resInterceptors &&
						typeof _this.resInterceptors === 'function'
					) {
						let resInterceptors = _this.resInterceptors(res)
						if (!resInterceptors) {
							reject('返回值已被您拦截!')
							return
						} else if (
							Object.prototype.toString.call(resInterceptors) ===
							'[object Promise]'
						) {
							// console.log('run1')
							try {
								// console.log('run2')
								let promiseRes = await resInterceptors
								resolve(promiseRes)
							} catch (error) {
								reject(error)
							}
						} else {
							// console.log('run3',{...resInterceptors})
							res = resInterceptors
						}
					}
					// console.log('接口返回值',{...res})
					resolve(res)
				}
			})
		})
	}
	_formatUrl(baseUrl, url) {
		if (!baseUrl) return url
		let formatUrl = ''
		const baseUrlEndsWithSlash = baseUrl.endsWith('/')
		const urlStartsWithSlash = url.startsWith('/')
		if (baseUrlEndsWithSlash && urlStartsWithSlash) {
			formatUrl = baseUrl + url.substring(1)
		} else if (baseUrlEndsWithSlash || urlStartsWithSlash) {
			formatUrl = baseUrl + url
		} else {
			formatUrl = baseUrl + '/' + url
		}
		return formatUrl
	}
	_merge(oldConfig, newConfig) {
		let mergeConfig = this._deepCopy(oldConfig)
		if (!newConfig || !Object.keys(newConfig).length) return mergeConfig
		for (let key in newConfig) {
			if (key !== 'header') {
				mergeConfig[key] = newConfig[key]
			} else {
				if (
					Object.prototype.toString.call(newConfig[key]) === '[object Object]'
				) {
					for (let headerKey in newConfig[key]) {
						mergeConfig[key][headerKey] = newConfig[key][headerKey]
					}
				}
			}
		}
		return mergeConfig
	}
	_deepCopy(obj) {
		let result = Array.isArray(obj) ? [] : {}
		for (let key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (typeof obj[key] === 'object') {
					result[key] = this._deepCopy(obj[key])
				} else {
					result[key] = obj[key]
				}
			}
		}
		if (Object.keys(result).length == 0) result = obj || null
		return result
	}
}

if (!global.$request) {
	global.$request = new Request()
}
// 设置请求拦截器
global.$request.interceptors.request(config => {
	// console.log("你大爷的")
	// config.header['WX-MINI-TOKEN']=store.state.token?store.state.token:""
	// console.log(config,store,"config")
	// 配置参数和全局配置相同,此优先级最高,会覆盖在其他地方的相同配置参数

	// 追加请求头,推荐
	// config.header['content-type'] = 'application/json';
	// config.header.token = 'token from interceptors';
	// if(res.header['WX-MINI-TOKEN']){
	// 	uni.setStorageSync('wxToken', res.header['WX-MINI-TOKEN'])
		
	// }
	// console.log()
	
	// 覆盖请求头
	// config.header = {
	// 'content-type': 'application/json',
	// 'token': 'token from interceptors'
	// }

	// return false; // 终止请求
	// return Promise.reject('error from request interceptors'); // 向外层抛出错误,用catch捕获
	return config // 返回修改后的配置,如未修改也需添加这行
})

// 设置响应拦截器
global.$request.interceptors.response(res => {
	// console.log('设置响应拦截器', res)
	// 接收请求,执行响应操作
	// 您的逻辑......
	// 'WX-MINI-TOKEN':uni.getStorage({key:'wxToken'})?uni.getStorage({key:'wxToken'}):''
     // console.log(res,"res")
	
	 

	// return false;    // 阻止返回,页面不会接收返回值
	// return {message: '自定义值,来自拦截器'};   // 返回您自定义的值,将覆盖原始返回值
	// return Promise.reject('error from response interceptors') // 向外层抛出错误,用catch捕获
	if (res.data) {
		// if (res.data.code && res.data.code != 0)
		// 	uni.showToast({
		// 		title: res.data.message,
		// 		icon: "none"
		// 	})
	}

	return res.data // 原样返回
})
export default global.$request

5.http.js请求路径分类


import config from './api.js'
import request from './conom.js'


export const apis = {
	bindMember:'/zimman/config/get',
}
export const bindMember = params => request.get(apis.bindMember +'/'+ params).then(res => res)

6.全局注册main.js

import http from './api/http.js'
Vue.prototype.http = http

7.引入页面方式

import {bindMember} from '../../api/http.js'
	export default {
		onLoad() {
			this.tyu()
		},
		methods: {
			tyu(){
				let params='abbout_us'
				bindMember(params).then(res=>{
				  console.log(res);
				})
			}
		}
	}

你可能感兴趣的:(vue.js,前端,uni-app)