创建common目录,建立request.js文件,代码如下:
const baseUrl = 'http://111.1111.111.11:xxxx/Api/'
// 封装请求 传入url data(get请求参数也在这里) type
export const myRequest =(options)=>{
return new Promise((resolve,reject)=>{
uni.request({
url:baseUrl + options.url,
method:options.method || 'GET',
data: options.data || {},
header: options.header ||{},
success: (res) => {
uni.showToast({
title:'请求接口成功'
}),
resolve(res)
},
fail: (err) => {
uni.showToast({
title:'请求接口失败'
}),
reject(err)
}
})
})
}
main.js中导入并挂载
import {myRequest} from 'common/request.js'
Vue.prototype.$myRequest =myRequest;
页面请求示例
methods: {
async getList() {
// post请求
const param = {
"loginName": "admin",
"password": "admin",
};
const res = await this.$myRequest({
url: 'Login/UserLogin',
method: 'Post',
data: param
})
console.log(res.data)
// get请求
const param1 = {
"pageIndex": "1",
"pageSize": "11",
};
console.log('get请求')
const res1 = await this.$myRequest({
url: 'Factory/GetList',
method: 'GET',
data: param1
})
console.log(res1.data)
}
}