小程序网络请求封装
1.简易版
import settingFile from '@/setting.js' //公共路径 {host: 'https://公共路径'}
function http(options) {
return new Promise((resolve, reject) => {
var setting = {
url: settingFile.host + options.url,
data: options.data,
method: options.method.toUpperCase() || 'GET',
// timeout: 6000,
header: {
// 'content-type': 'application/x-www-form-urlencoded',
},
success(res) {
resolve(res.data);
},
fail(err) {
console.log('err', err);
reject(err);
},
}
if (options.header) {
setting.header = Object.assign(setting.header, options.header);
}
wx.request(setting);
})
}
export default http;
import request from '@/api/request.js' .引入上面文件
const apis={
1:'/swiperIndex',
2:'/homeFL',
3:'/homeAuthor',
4:'/newFb',
5:'/homeRx'
}
function swiperList(data){
return request({
url: apis[1],
method: 'get',
data
})
}
function homeFLList(data){
return request({
url: apis[2],
method: 'get',
data
})
}
function homeAuthor(data){
return request({
url: apis[3],
method: 'get',
data
})
}
function newFb(data){
return request({
url: apis[4],
method: 'get',
data
})
}
function Rx(data){
return request({
url: apis[5],
method: 'get',
data
})
}
export default {
swiperList,
homeFLList,
homeAuthor,
newFb,
Rx
}
在使用页面引入
import api from '@/api/apis.js'; 文件2
getFlList() {
api.homeFLList().then(res => {
.......
});
},
2.心疼giegie版
1.创建个js文件
function promiseHttp(api) {
return (option = {}) => {
return new Promise((resolve, reject) => {
api({
...option,
success: resolve,
fail: reject,
})
})
}
}
var a = ['request']//可以放一些其他的api
function promiseReq() {
wx.giegie = {}; //自定义名字
Object.keys(wx).forEach((function (e) {
if (a.indexOf(e) >= 0) {
wx.giegie['request'] = promiseHttp(wx.request)
}
}))
};
export {
promiseReq,
promiseHttp
};
2.在 app.js 中引入
import { promiseReq} from './utils/apis/addPro' 上述文件
promiseReq()
3.封装请求
const app = getApp()
const BaseUrl = 'http://...'
const whiteList = [
'/api/...'
]
const request = (params = {}) => {
// 拦截
if (!whiteList.includes(params.url)) {
params.header = {
// 'content-type': 'application/json',
'token': app.globalData.token || ''
}
}
if (params.url.startsWith('/')) {
params.url = BaseUrl + params.url
}
return wx.giegie.request({
...params
})
//成功
.then(res => {
return Promise.resolve(res)
})
//失败
.catch(err => {
console.log(err)
return Promise.reject(err)
})
}
export {
request
}
4.网络请求管理
import {
http
} from './request.js'
const getList = () => http({
url: '/api/...',
method: 'POST'
})
const getList2 = () => http({
url: '/api/...',
method: 'POST'
})
export default {
getList,
getList2
}
5.使用
import api from '../../utils/apis/api' 引入4文件
api.getList().then(res => {
console.log(res)
})
写法巨拉胯