新建文件
现在src中新建一个api目录
新建index.js和request.js文件
配置方法发送请求
request.js中输入以下内容
const http = {
baseUrl: 'http://127.0.0.1:8000',
request(config) {
config = beforeRequest(config)
config.url = this.baseUrl + config.url
return new Promise((resolve, reject) => {
uni.request(config)
.then(res => {
let [error, resp] = res
const response = beforeResponse(resp)
resolve(response)
})
.catch(err => {
errorHandle()
reject(err)
})
})
},
get(url, params, auth){
return this.request({
url: url,
data: params,
method: "GET",
auth:auth,
header: {
'content-type': 'application/json',
}
})
},
post(url, data, auth) {
return this.request({
url: url,
data: data,
method: "POST",
auth: auth,
header: {
'content-type': 'application/json',
}
})
},
}
// 请求拦截器
const beforeRequest = (config) => {
// if (config.auth) {
// const token = uni.getStorageSync('token')
// config.header.Authorization = token
// }
return config
}
// 响应拦截器
const beforeResponse = (resp) => {
if (resp.statusCode === 200) {
return resp.data
} else {
errorHandle(resp)
}
}
// 异常处理器
const errorHandle = (err) => {
console.log('网络异常,请求失败',err);
}
index.js配置接口
import http from './request.js'
export default {
// 获取首页数据
getHomeData() {
return http.get('/api/index',{},true)
},
// 获取分类数据
postCategoryData() {
return http.post('/api/category',{},true)
},
}
使用
页面中使用
import { getHomeData, postCategoryData} from '@/api/index'
async getHomeData(list) {
const { data } = await getHomeData('pinyin')
},
您好,我是肥晨。
欢迎关注我获取前端学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。