參考博客:
(1)wx-request封裝:https://www.jianshu.com/p/ad1...
(2)setData()方法的使用和注意事項:https://blog.csdn.net/qq_3859...html
在app.js下配置host域名web
// wx.request封裝 const app = getApp() const request = (url, options) => { return new Promise((resolve, reject) => { wx.request({ url: `${app.globalData.host}${url}`,//獲取域名接口地址 method: options.method, //配置method方法 data: options.method === 'GET' ? options.data : JSON.stringify(options.data), //若是是GET,GET自動讓數據成爲query String,其餘方法須要讓options.data轉化爲字符串 header: { 'Content-Type': 'application/json; charset=UTF-8', 'token':token }, //header中能夠監聽到token值的變化 success(request) { //監聽成功後的操做 if (request.data.code === 10000) { //此處10000是項目中數據獲取成功後返回的值,成功後將request.data傳入resolve方法中 resolve(request.data) } else { //若是沒有獲取成功返回值,把request.data傳入到reject中 reject(request.data) } }, fail(error) { //返回失敗也一樣傳入reject()方法 reject(error.data) } }) }) } //封裝get方法 const get = (url, options = {}) => { return request(url, { method: 'GET', data: options }) } //封裝post方法 const post = (url, options) => { return request(url, { method: 'POST', data: options }) } //封裝put方法 const put = (url, options) => { return request(url, { method: 'PUT', data: options }) } //封裝remove方法 // 不能聲明DELETE(關鍵字) const remove = (url, options) => { return request(url, { method: 'DELETE', data: options }) } //拋出wx.request的post,get,put,remove方法 module.exports = { get, post, put, remove }
const getMainPage = 'api/mainPage/getMainPage' // 獲取首頁資源 //拋出getMainPage這個常量 module.exports = { getMainPage }
import { getMainPage} from '../api/api.js' import api from '../../utils/request.js'
/** * 生命週期函數--監聽頁面加載 */ onLoad: function(options) { //調用接口 api.post(getMainPage).then(res => { //成功時回調函數 console.log(res) }).catch(err => { //失敗時回調函數 console.log(err) }) },
備註:json
必須使用setData()來觸發數據的更新
緣由:
能夠參考官網地址: https://developers.weixin.qq....小程序
Page.prototype.setData(Object data, Function callback)板塊api