创建请求文件http.js
var api_base_url = "this is url"; export default function ({ url, data = {}, method = "GET" }) { return new Promise((resolve, reject) => { let contentType = method == ‘POST‘ ? ‘application/x-www-form-urlencoded‘ : ‘application/json‘; wx.request({ url: api_base_url + url, method: method, data: data, header: { "content-type": contentType, }, success: (res) => { const code = res.statusCode.toString(); if (code.startsWith(‘2‘)) { resolve(res.data) console.log("success", res.data) } else { reject(res.data) console.log("error", res.data) } }, fail: (err) => { console.log("fail", err) } }) }) }
创建公共接口文件 api.js
import http from ‘./http.js‘ function getSuccessData(params) { return http({ method: ‘GET‘, url: ‘url‘, data: params }) } function postFormData(params){ return http({ method: ‘POST‘, url: ‘url‘, data: params }) } export { getSuccessData, postFormData }
使用
import { getSuccessData, postFormData } from ‘../../utils/api.js‘ Page({ data: {}, onLoad: function(options) { this.getData() }, //获取数据 getData() { let data = { utoken: "utoken_e6edde9df7cb836b2ceb04b2228505c0", i: 170 } getSuccessData(data).then(result => { console.log(result) return postFormData({id: "11"}).then((res)=>{ console.log(res) }) }) }, onReady: function() {}, onShow: function() {}, onHide: function() {}, onUnload: function() {}, onPullDownRefresh: function() {}, onReachBottom: function() {}, onShareAppMessage: function() {} })