长话不多说,上代码
根目录下新建api目录 (cli创建项目的是src目录下),内部新建request.js文件 和index.js文件
request.js做为请求接口文件
// 区分开发环境和生产环境
var baseUrl;
if (process.env.NODE_ENV === 'development') {
baseUrl = 'https://www.test.com'
} else {
baseUrl = 'https://www.baidu.com'
}
export function request(config) {
// 请求时间 超出时间抛出错误
config.timeout = 20000;
//
config.header = {
'content-type': 'application/json',
// 'token': 'hello' //token
};
config.url = baseUrl + config.url;
let promise = new Promise(function(resolve, reject) {
uni.request(config).then(res => {
if (res[0]) {
uni.showToast({
title: "数据获取失败",
icon: "none",
duration: 1500
})
resolve(false);
// reject({
// message: res[0],
// config: config
// });
} else {
let data = res[1].data; // 如果返回的结果是data.data的,嫌麻烦可以用这个,return res,这样只返回一个data
if (data.code == 1) {
resolve(data);
} else {
resolve(data);
// return uni.showToast({
// title:data.msg,
// icon:"none",
// duration: 500
// })
}
uni.hideLoading();
}
}).catch(error => {
uni.hideLoading();
reject(error);
})
})
return promise
}
index.js做为indexApi模块的接口集合
import {request} from '@/api/request.js'; // 引入封装好的request
class indexApi{
// 获取首页top nav
async columnIndex(data) {
const res = await request({
method: "get", // 请求方式
url: '/api/column/index', // 请求url
data: data,// 参数
})
return res
}
// 获取推荐
async recommendIndex(data){
const res = await request({
method: "POST", // 请求方式
url: '/api/recommend/index', // 请求url
data: data // 参数
})
return res
}
}
export default new indexApi()
页面上可以这样使用
import indexApi from '@/api/index.js';
onload(){
this.getDataA()
this.getDataB()
},
methods:{
// 同步方法 使用async await 语法糖
async getDataA(){
// post 参数
var parameter = {
city_name: '深圳',
tag: "推荐",
}
let res = await indexApi.recommendIndex(parameter)
console.log(res)
},
//异步方法
getDataB(){
// 没有参数为空即可
indexApi.columnIndex().then((res)=>{
console.log(res)
})
},
}