uni-app 项目 封装http 和url

需求分析:
封装http请求和url请求,蛀牙目的还是为了统一管理

将这两个部分放在http文件夹下面
http/http.js

//路由公共的部分:
const baseUrl = 'http://172.0.0.1:8080';
//不带token的封装
const httpRequest = (opts, data) => {  //opts 是一个对象,包含了后面的url,方法,请求头设置,返回的数据类型等
    //1.请求的一些默认信息
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		dataType: 'json',
	}
	//2.封装promise
	return new Promise((resolve, reject)=>{
		uni.request(httpDefaultOpts).then(
			(res) => {
				resolve(res[1])
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
};
//带Token请求
const httpTokenRequest = (opts, data) => {
	let token = "";
	uni.getStorage({
		key: 'token',
		success: function(ress) {
			token = ress.data
		}
	});
	//此token是登录成功后后台返回保存在storage中的
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'Token': token,
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'Token': token,
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		dataType: 'json',
	}
	return  new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				resolve(res[1])
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
};

export default {
	baseUrl,
	httpRequest,
	httpTokenRequest
}

在main.js中全局挂载

import Vue from 'vue'
import App from './App'
import myRequest from './http/http.js'

Vue.prototype.$http = myRequest
Vue.config.productionTip = false
App.mpType = 'app'

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

在页面中使用

let opts = {
	url: '/api/add',
	method: 'post'
};
let param = {
	deviceId: this.deviceCode,
	deviceName: this.deviceName
};
this.$myRequest.httpTokenRequest(opts, param).then(res => {
	console.log(res.data);
	//打印请求返回的数据

}, error => {
	console.log(error);
})
上一篇:Ansible 管理Windows Server遇到的问题


下一篇:数据可视化 - 漏斗流量转化分析图