方式一:
1坪它、在小程序的目錄下新建一個(gè) api 的文件夾
2:在 api 文件夾中新建一個(gè) config.js 文件朴沿,用于存放公共的服務(wù)器地址夫晌,內(nèi)容如下:
const baseUrl = 'https://www.baidu.com/';
export {
baseUrl
}
3:在 api 文件夾中新建一個(gè) request.js 文件读第,用于存放封裝的api請(qǐng)求颠印,內(nèi)容如下:
import { baseUrl } from './http.js'
module.exports = {
/*
* url:請(qǐng)求的接口地址
* methodType:請(qǐng)求方式
* data: 要傳遞的參數(shù)
*/
request : function(url, methodType, data){
let fullUrl = `${baseUrl}${url}`
let token = wx.getStorageSync('token') ? wx.getStorageSync('token') : ''
wx.showLoading({ title: "加載中" });
return new Promise((resolve,reject)=>{
wx.request({
url: fullUrl,
method:methodType,
data,
header: {
'content-type': 'application/json', // 默認(rèn)值
'x-api-key': token,
},
success: (res) => {
if (res.data.status == 200) {
resolve(res.data)
}else{
wx.showToast({
title: res.data.msg,
icon:'none'
})
reject(res.data.message)
}
},
fail: () => {
wx.showToast({
title: '接口請(qǐng)求錯(cuò)誤',
icon:'none'
})
reject('接口請(qǐng)求錯(cuò)誤')
},
complete: () => {
setTimeout(() => {
wx.hideLoading()
}, 100)
}
})
})
}
}
4:在 api 文件夾中新建一個(gè) index.js 文件纲岭,用于存放api請(qǐng)求的地址,內(nèi)容如下:
import { request } from './request'
module.exports = {
// 獲取企業(yè)列表
getCompanyList: (data) => request('/company/getlist', 'GET', data),
}
5:在文件中使用线罕,內(nèi)容如下:
// 引入 api 下的 index 文件
const $api = require('../../api/index')
// 在方法中調(diào)用
goList(){
let data = {
aaa: this.data.cardCur,
bbb: this.data.notice,
}
$api.getCompanyList(data).then((res) => {
console.log(res,'res');
})
},
方式二:
前3步是一樣的止潮,區(qū)別就是封裝請(qǐng)求的不同
封裝所有請(qǐng)求 api/http.js
//引入封裝的reuest請(qǐng)求
const {
request
} = require('./request.js')
//基于業(yè)務(wù)封裝的接口
module.exports = {
// 登錄
getLogin: (data) => {
return request('/***/***/***/login', 'POST', data);
},
// 獲取企業(yè)信息
getCompanyList: (data) => {
return request('/***/***/***/Company', 'GET', data);
},
}
使用
// 引入登錄接口
import {
getLogin
} from '../../api/http.js'
Page({
data: {
username: '',
pwd: ''
},
onLoad() {
let params = {
username: this.data.username,
pwd: this.data.pwd
}
// 登錄
getLogin(params).then(res => {
wx.setStorageSync('Cookie', res.cookies[0])
wx.switchTab({
url: '../index/index'
})
})
},
// 退出登錄
handleLogOut() {
wx.clearStorageSync()
wx.navigateTo({
url: '../login/login'
})
},
})