一、在根目录下创建config.js
的js文件和api
的文件夹下创建http.js
的js文件
***
config.js文件
const config = {
api_base_url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata',
//若后端要求传入
// appkey:'kkkkkkkkooooo'
}
// let fun1=function(){
// }
export {
config
} //es6 模块导出 => export{config,fun1,config2,...,config as cfig}
http.js文件
import {
config
} from '../config.js' //es6 模块导入 =>import {导入名称} from '路径'
//错误码 根据项目确定
const tips = {
1: '抱歉,出现了一个错误,请联系客服',
1001: '用户名无效',
3001: '用户不存在'
}
class HTTP {
request(params) {
// url,data,method
if (!params.method) {
params.method = 'GET'
}
wx.request({
url: config.api_base_url,
data: params.data,
method: params.method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
"content-type": "application/json",
"appkey": config.appkey
}, // 设置请求的 header
success: (res) => {
// success
//服务器返回的state状态码还是会在success中处理
let code = res.statusCode.toString()
if (code.startsWith('2')) {
params.success(res.data)
} else {
//其他错误异常信息给用户展示提示信息
// wx.showToast({
// title: '错误',
// icon: 'none',
// duration: 2000
// })
let error_code = res.data.error_code
this._show_error(error_code)
}
},
fail: (err) => {
this._show_error(1)
},
complete: function () {
// complete
}
})
}
_show_error(error_code) {
if (!error_code) {
error_code = 1
}
wx.showToast({
title: tips[error_code],
icon: 'none',
duration: 2000
})
}
}
export {
HTTP
}
http.js文件
// pages/index.js
import {HTTP} from '../../api/http.js'
//实例化class类
let http=new HTTP()
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
http.request({
success: (res)=> {
console.log(res.message);
}
})
// wx.request({
// url: 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata',
// data: {},
// method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: { appkey: "111"}, // 设置请求的 header
// success: function(res){
// console.log(res);
// },
// fail: function(res) {
// console.log(res);
// },
// complete: function() {
// // complete
// }
// })
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})