新建文件
在util文件夹下新建文件requestMethod.js
requestMethod.js具体代码
let serverPath = 'http://192.168.2.236/' //根据你自己的接口rul来
let apiReq={
post(url,body) {
let token = wx.getStorageSync('token') || ''; //请求接口固定参数,根据需要来
return new Promise((resolve,reject) => {
uni.request({
url: serverPath + url, // 拼接完整的url
data: body,
method:'POST',
header: {
'content-type': 'application/json',
'token':token
},
success(res) {
resolve(res.data) // 把返回的数据传出去
},
fail(ret) {
reject(ret) // 把错误信息传出去
}
})
})
}
}
export default apiReq
修改main.js以供方法全局使用
import Vue from 'vue'
import apiReq from './utils/requestMethod.js'
Vue.prototype.$post = apiReq.post
项目里使用示例
html部分
<div @click="getUserInfo"></div>
js部分
methods: {
async getUserInfo() {
var that = this;
let res = await this.$post("user/info", { id: that.id });
that.name = res.user.username;
},
}
大功告成,愉快的使用吧