在uniapp中,使用promise对get,post请求进行封装
var rootUrl = 'https://192.168.0.125:8085'; // 你的域名
// 统一请求封装
function req(method, url, data) {
if (method === 'get') {
var promise = new Promise((resolve, reject) => {
var that = this;
uni.request({
url: rootUrl + url,
data,
method,
dataType: "json",
header: {
"content-type": "application/json"
},
success: function(res) {
console.log('getReq', res)
if (res.statusCode == 200) {
resolve(res.data);
} else {
resolve(res.data);
}
},
error: function(e) {
reject("网络出错");
}
});
});
return promise;
}else{
var promise = new Promise((resolve, reject) => {
var that = this;
uni.request({
url: rootUrl + url,
data,
method,
header: {
"content-type": "application/x-www-form-urlencoded",
token: uni.getStorageSync("token")
},
success: function(res) {
console.log('postReq', res)
//返回什么就相应的做调整
if (res.statusCode == 200) {
resolve(res.data);
} else {
// 请求服务器成功,但是由于服务器没有数据返回,此时无code。会导致这个空数据
// 接口后面的then执行
// 不下去,导致报错,所以还是要resolve下,这样起码有个返回值,
// 不会被阻断在那里执行不下去!
resolve(res.data.msg);
}
},
error: function(e) {
reject("网络出错");
}
});
});
return promise;
}
}
// 必须使用module.export的形式进行导出
module.exports = {
req: req
}
然后需要把promise封装的req函数,挂载到Vue的原型上。
在main.js中,插入以下代码即可:
// 引入封装好的js文件
import http from './serve/http.js'
Vue.prototype.$http = http
最后,进行接口请求即可。
// xxx.vue文件的js代码
<script>
export default {
data() {
return {
}
},
onLoad() {
this.indexContent()
this.login()
},
methods: {
indexContent() {
this.$http.req('get', '/api/home/content', '').then(res => {
console.log(res)
})
},
login() {
this.$http.req('post', '/api/sso/login', {
'username': '18888888888',
'password': '123456'
}).then(res => {
console.log(res)
})
}
}
}
</script>
在此接口的调试过程中,可能会出现跨域请求不到接口的问题,我们只需设置以下代理即可。
打开uniapp项目目录,找到manifest.json文件,源码视图中加入以下代码即可,解决跨域问题。
"h5": {
"devServer": {
"proxy": {
"/api": {
"target": "http://localhost:8081/api",
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
}
}
}
如下图:

网友评论