首先,我們?cè)诟夸浵葎?chuàng)建一個(gè)request 文件夾
然后里面一共分為三個(gè)部分1 .request.js 2. api.js 3. fetch.js 那我們來(lái)一起看看里面的代碼
1 .request.js的代碼
function request(params) {
// 封裝網(wǎng)絡(luò)請(qǐng)求的代碼
return new Promise(function (resolve, reject) {
wx.request({
url: params.url,
data: params.data || {},
header: params.header || {},
method: params.method || 'GET',
dataType: 'json',
success: function(res) {
resolve(res.data)
},
fail: function(err) {
wx.showToast({
title: err || '請(qǐng)求錯(cuò)誤!',
})
reject(err)
}
})
})
}
// nodejs common
module.exports = {
requestApi: request
}
- api.js
var baseUrl = 'http://192.168.113.113:8637' //這里請(qǐng)輸入你自己的接口地址
// 測(cè)試的服務(wù)器
// var baseUrl = 'http://192.168.113.116:8637'
// 正式環(huán)境
// var baseUrl = 'http://www.mysite.com'
var homeApi = baseUrl + '/xm/home' //接口地址+接口的接口API
var loginApi = baseUrl + '/wx/login' //接口地址+接口的接口API
// 導(dǎo)出
module.exports = {
homeApi: homeApi,
loginApi: loginApi
}
- fetch.js
// 引入兩個(gè)文件
var api = require('./api.js')
var request = require('./requst.js')
// get請(qǐng)求的的模板
function getHome(params) {
return request.requestApi({
url: api.homeApi // 文件名+ 接口
})
}
// post請(qǐng)求的模板
function LoginFn(params) {
return request.requestApi({
url: api.loginApi, // 文件名+ 接口
data: params,
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST'
})
}
// 導(dǎo)出
module.exports = {
getHome: getHome,
LoginFn: LoginFn
}
接下來(lái)我們就可以在需要引用的頁(yè)面直接引用了
const fetch = require('../../request/fetch')
然后我們就可以在頁(yè)面通過(guò) fetch .getHome() 調(diào)用
實(shí)例
// get
fetch.getHome({
Page: 1,
size: 10,
}).then(res => {
console.log(res);=
})
// post
fetch.LoginFn({
username:'wx',
pwd:'wx'
}).then(res=>{
console.log(res);
})