uni-app小程序接口封裝
1摊趾、在src下新建api文件夾
2币狠、在api文件夾下創(chuàng)建http.js
(如果BASE_URL有多個,可重新建文件導(dǎo)入砾层,此處放在同一個文件中)
http.js文件
const BASE_URL = 'https://xxx.xxx.com' //域名
export const uniRequest = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: options.baseUrl ? options.baseUrl + options.url : BASE_URL + options.url,
method: options.method || 'GET', // 收請求的方式,如果不傳默認(rèn)為GET
data: options.data || {}, // 接收請求的data,不傳默認(rèn)為空
dataType: options.dataType,
header: options.headers,
success: (res) => { //數(shù)據(jù)獲取成功
if (res.statusCode == 200) {
resolve(res) // 成功,將數(shù)據(jù)返回
} else { // 失敗信息
uni.showToast({
title: res.errMsg || '請求接口失斪苎啊!',
icon: 'error'
})
}
},
fail: (err) => { // 失敗操作
uni.showToast({
title: "請求接口失斏椅渐行!",
icon: 'error'
})
reject(err)
}
})
})
}
在main.js中引入
import { uniRequest } from './api/http.js'
Vue.prototype.$uniRequest = uniRequest
頁面中使用
this.$uniRequest({ // 調(diào)用封裝好的API請求函數(shù)
// baseUrl:'域名',
url: '/yuasa/openApi/selectData.do', // 把接口傳過去
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
domain: 'xxx',
text: 'xxx',
},
dataType: "json",
}).then(res => {
console.log(res)
}).catch(res => {
uni.showToast({
title: res.msg,
icon: 'error'
})
})