新建httpService.js
let http = {
'baseUrl':'http://120.79.22.16',//测试url地址
'uploadURL':'/uploadify/upload',
'getfileURL':'/kindeditor/initfiles',
'get': get,
'post': post,
'uncookieRequest':uncookieRequest
}
function httpRequest (opts,data){ //无token请求
let httpDefaultOpts = {
url: http.baseUrl+opts.url,
data: data,
method: opts.method,
header: opts.method == 'get' ? {
"Content-Type": "application/json; charset=UTF-8"
} : {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
dataType: 'json',
}
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
console.log(res)
resolve(res[1])
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
}
function httpTokenRequest(opts,data){ //token请求
var headers = '';
var token = uni.getStorageSync('JwtToken');
if(opts.method == 'get'){
headers = {
'JwtToken': token,
"Content-Type": "application/json; charset=UTF-8"
}
}else{
if(opts.formcode){
headers = {
'JwtToken': token,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}else{
headers = {
'JwtToken': token,
"Content-Type": "application/json; charset=UTF-8"
}
}
}
let httpDefaultOpts = {
url: http.baseUrl+opts.url,
data: data,
method: opts.method,
header: headers,
dataType: 'json',
}
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
resolve(res[1])
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
}
function post(url,data,form){ //post请求——form为true是表单类型,不需要的可以去掉
let opts={
url: url,
method: 'post',
formcode: form ? form : false
};
return httpTokenRequest(opts, data)
}
function get(url,data){//get请求
let opts={
url: url,
method: 'get'
};
return httpTokenRequest(opts,data)
}
function uncookieRequest(url,data){//无token请求
let opts={
url: url,
method: 'post'
};
return httpRequest(opts, data)
}
export default http
main.js
在mian.js 通过import 引入./httpService.js中的对象,将其注册到Vue的原型对象上
import Vue from 'vue'
import App from './App'
import chart from './common/chart.js'
import tools from './common/tools.js'
import util from './common/util.js'
import httpService from './common/httpService.js'
Vue.config.productionTip = false
App.mpType = 'app'
Vue.prototype.$httpService = httpService;
Vue.prototype.$httpService = httpService;
Vue.prototype.$chart = chart;
Vue.prototype.$tools = tools;
Vue.prototype.$util = util;
const app = new Vue({
...App
})
app.$mount()
index.vue运用
注:写url时只需要"/xxx"
this.$httpService.post('',‘’,true).then(res => {
console.log(res );}
},error => {
console.log(error);
});
通过 async+await 同步语法实现异步请求
在vue页面上
async xxx(){ //定义
const res= await this.$httpService.post('',‘’,true)
console.log(res)
}
xxxx(){//运用
var xx= this.xxx();
Promise.resolve(xx).then(function (result) {
console.log(result)
})
}
在tool.js
引入httpService.js
import http from './httpService.js'
async function getUserName(id){ //获取用户名
const response = await http.post('','','');
return response;
}