即时焦点:微信小程序请求封装
来源:腾讯云时间:2023-03-08 06:09:37


(相关资料图)

config.js

const baseUrl = "http://127.0.0.1:8000/";export {  baseUrl}

index.js

import {  request} from "./request"module.exports = {  // 获取导航  getNavList: (data) => request("nav/", "GET", data),}

request.js

import {  baseUrl} from "./config.js"module.exports = {  /*   * url:请求的接口地址   * methodType:请求方式   * data: 要传递的参数   */  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", // 默认值          "x-api-key": token,        },        success: (res) => {          if (res.statusCode == 200) {            resolve(res.data)          } else {            wx.showToast({              title: res.data.msg,              icon: "none"            })            reject(res.data.message)          }        },        fail: () => {          wx.showToast({            title: "接口请求错误",            icon: "none"          })          reject("接口请求错误")        },        complete: () => {          setTimeout(() => {            wx.hideLoading()          }, 100)        }      })    })  }}

pages/index/index.js

onLoad() {    this.goList()  },  // 在方法中调用  goList() {    let data = {}    $api.getNavList(data).then((res) => {      console.log(res, "res");    })  },

关键词: