調(diào)用文檔里面提供的方法:直接搜索Request 就行 選中 wx.request 那一項
請求地址:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
<-- html -->
<button type="primary" bindtap="demoGETfn">GET請求</button>
<button type="warn" bindtap="demoPostfn">Post請求</button>
// index.js頁面
// Ge請求
demoGETfn(){
// 查文檔
// 拿到接口,再‘’‘’‘’‘’‘’‘’‘’‘’‘’‘根據(jù)接口參數(shù) 做請求
wx.request({
url: 'https://api.readhub.cn/topic',
data: {
pageSize: 10,
},
success (res) {
console.log(res)
}
})
},
// Post請求
demoPostfn(){
wx.request({
url: 'http://kumanxuan1.f3322.net:8001/auth/loginByWeb',
method: "Post",
data:{
username: "wx",
pwd: "wx",
},
// 這里沒有Promise風(fēng)格的寫法
success(res){
console.log(res);
}
})
},
再來說一下數(shù)據(jù)請求的封裝
1.先寫一個require文件
function request(params) {
// 封裝網(wǎng)絡(luò)請求的代碼
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 || '請求錯誤!',
})
reject(err)
}
})
})
}
// nodejs common
module.exports = {
requestApi: request
}
2.再用一個api.js文件接收
//(這里的服務(wù)器地址可以根據(jù)需求 進(jìn)行替換)
// 開發(fā)的服務(wù)器
var baseUrl = 'http://kumanxuan1.f3322.net:8001'
// 測試的服務(wù)器
// var baseUrl = 'http://192.168.113.116:8637'
// 正式環(huán)境
// var baseUrl = 'http://www.mysite.com'
var homeApi = baseUrl + '/topic/list'
var loginApi = baseUrl + '/auth/loginByWeb'
module.exports = {
homeApi: homeApi,
loginApi: loginApi
}
3.在fetch.js文件里面寫入接口函數(shù)并導(dǎo)出:
var api = require('./api.js')
var request = require('./requst.js')
function getHome(params) {
return request.requestApi({
url: api.homeApi
})
}
function LoginFn(params) {
return request.requestApi({
url: api.loginApi,
data: params,
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST'
})
}
module.exports = {
getHome: getHome,
LoginFn: LoginFn
}
這樣就完成了數(shù)據(jù)請求的封裝, 后面的只要引用就行了。
如何引入
因為請求是向服務(wù)端發(fā)送的代碼, 所以用 - require引入
const fetch = require('../../request/fetch');
在方法里面調(diào)用
// Get請求
// 看文檔
demoGETfn(){
fetch.getHome({
page:1,
size:20
}).then(res => {
console.log(res);
})
},
// Post請求
demoPostfn(){
fetch.LoginFn({
username: "jx",
pwd: "jx"
}).then(res => {
console.log(res);
})
},