1.在项目的根目录下创建Common文件夹,用于存放以下的JavaScript文件。
2.在Common目录创建:baseconfig.js。代码如下:
var baseconfig={};
if(process.env.NODE_ENV === 'development'){
baseconfig = {
server:开发时IP:端口号
}
}else if(process.env.NODE_ENV === 'production'){
baseconfig = {
server:生产时IP:端口
}
}
export default baseconfig;
3.继续创建httpClient.js文件,定义了两种请求get和post
import baseconfig from './baseconfig.js'
const httpClient = {
request: function(method, url, data) {
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
// "Auth-Token": uni.getStorageSync("auth_token")
};
var nowDate = new Date().getTime();
return new Promise((resolve, reject) => {
uni.request({
url: url,
header: headers,
data: data,
method: method,
dataType: 'json',
success: function(res) {
console.log("接口获取原始数据:---->", res.data, nowDate)
if (res.statusCode == 200) {
let result = res.data
if (result.code === 0) {
resolve(result)
return;
}
if (result.msg != null && result.msg != "") {
reject(result.msg);
}
}
},
fail: function(err) {
if (err.errMsg != 'request:fail abort') {
reject('连接超时,请检查您的网络')
}
}
})
})
},
Get: function(url, data) {
let allurl = this.geturl(url);
return this.request('GET', allurl, data)
},
Post: function(url, data) {
let allurl = this.geturl(url);
return this.request('POST', allurl, data)
},
geturl: function(url) {
return baseconfig.server + url
}
};
module.exports = httpClient
4.继续创建api.js, 此js方法注册到全局vuex
import httpClient from './httpClient.js'
export function get(url,params){
return httpClient.Get(url,params)
};
export function post(url,params){
return httpClient.Post(url,params)
};
5.根目录main.js修改, 注册后在vue文件可以this.apiget直接调用。
import Vue from 'vue'
import App from './App'
import store from './store'
import {get,post} from "./common/api.js"
Vue.prototype.apiget = get
Vue.prototype.apipost = post
Vue.config.productionTip = false
Vue.prototype.$store = store
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount()
6. demo.vue文件中调用
methods: {
minfo() {
let that = this
that.apiget('/broker/my/info/dealer', {}).then(res => {
that.dealer = res.dealer
});
}
},