uniapp---uni.request的封装
1.首先我们先创建文件夹utils/request.js,封装
const url_all = {
'DEV': 'http://localhost:3001', //所需要填写的地址
}
let BASEURL = process.env.NODE_ENV === 'development' ? '/api' : url_all['DEV'] //判断是开发还是生产环境
const token = uni.getStorageSync('token')
const request = (options = {}) => {
return new Promise((resolve, rejects) => {
uni.request({
url: BASEURL + options.url,
method: options.method || 'GET',
data: options.data || '',
header: {
'token': token,
},
success: (response) => {
return resolve(response.data)
},
fail: (fail) => {
console.log('fail', fail)
return rejects(fail);
}
})
})
}
export default request
2.在api/api.js,文件里新增api
import request from '../utils/request.js'
let bsUrl = '/estate'
//通知公告
export const noticeAndAnnouncement =(options)=>{
return request({
url: bsUrl + '/v2/notice/search',
method:'GET',
data:options
})
}
3.页面调用
async noticeAndAnnouncement(){
try{
const res = await noticeAndAnnouncement({
communityId:JSON.parse(uni.getStorageSync('currentCommunity')).communityId,
})
const { rows, total } = res
}catch{
console.log('catch')
}
},
4.在manifest.json里做代理
在h5里面新增
"h5": {
"devServer": {
"open": false,
"https": true,
"port": 8080,
"proxy": {
"/api": {
"target": "需要代理的地址",
// "changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/api": "/api"
}
}
}
}
},