uni-app 请求封装

根目录新建util文件夹

新建request.js

import baseUrl from './config.js'

const request = {}
const headers = {}

request.globalRequest = (url, method, data, power) => {
	// 权限判断 因为有的接口请求头可能需要添加的参数不一样,所以这里做了区分
	    1 == 不通过access_token校验的接口
	    2 == 文件下载接口列表
	const userInfo = uni.getStorageSync('userInfo')
	switch (power) {
		case 1:
			headers['Authorization'] = 'Basic a3N1ZGk6a3N1ZGk='
			break;
		case 2:
			responseType = 'blob'
			break;
		default:
			headers['Authorization'] = userInfo.token
			break;
	}

	return uni.request({
		timeout:60000,
		url: baseUrl + url,
		method,
		data: data,
		dataType: 'json',
		header: headers
	}).then(res => {
		if (res.data.status && res.data.code == 200) {
			return res
		} else {
			throw res.data
		}
	}).catch(parmas => {
		switch (parmas.code) {
			case 401:
				uni.clearStorageSync()
				break
			default:
				uni.showToast({
					title: parmas.message,
					icon: 'none'
				})
				return Promise.reject()
				break
		}
	})
}
export default request

新建config.js配置请求地址

let baseUrl = ""
if (process.env.NODE_ENV === 'development') {
	baseUrl = 'https://jsonplaceholder.typicode.com'  // 开发环境
} else {
	baseUrl = 'https://jsonplaceholder.typicode.com' // 生产环境
}
export default baseUrl

请求资源/api/XXXX.js

import request from '@/common/request.js'
import {formatGetUrl} from '@/common/util.js'

const api = {}
// POST请求方式
api.login = () => request.globalRequest(`/posts`, 'POST', '', 1)
// GET请求方式
api.close = (params) => request.globalRequest(`/signUp?content=${params}`,'GET', {}, 1)

export default api

你可能感兴趣的:(uni-app请求封装,前端,javascript)