在uniapp中,使用promise對get乘客,post請求進行封裝
var rootUrl = 'https://192.168.0.125:8085'; // 你的域名
// 統(tǒng)一請求封裝
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("網(wǎng)絡(luò)出錯");
}
});
});
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)
//返回什么就相應(yīng)的做調(diào)整
if (res.statusCode == 200) {
resolve(res.data);
} else {
// 請求服務(wù)器成功狐血,但是由于服務(wù)器沒有數(shù)據(jù)返回,此時無code易核。會導(dǎo)致這個空數(shù)據(jù)
// 接口后面的then執(zhí)行
// 不下去匈织,導(dǎo)致報錯,所以還是要resolve下牡直,這樣起碼有個返回值缀匕,
// 不會被阻斷在那里執(zhí)行不下去!
resolve(res.data.msg);
}
},
error: function(e) {
reject("網(wǎng)絡(luò)出錯");
}
});
});
return promise;
}
}
// 必須使用module.export的形式進行導(dǎo)出
module.exports = {
req: req
}
然后需要把promise封裝的req函數(shù)碰逸,掛載到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>
在此接口的調(diào)試過程中胜榔,可能會出現(xiàn)跨域請求不到接口的問題,我們只需設(shè)置以下代理即可湃番。
打開uniapp項目目錄夭织,找到manifest.json文件,源碼視圖中加入以下代碼即可牵辣,解決跨域問題摔癣。
"h5": {
"devServer": {
"proxy": {
"/api": {
"target": "http://localhost:8081/api",
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
}
}
}
如下圖:
image.png