配置域名
一般情况下,项目中的域名前缀都是配置在 app.js 中

App({   onLaunch: function() {   },   globalData: {       userInfo: null,       loginCode: null,       version: '1.0.0',       host: 'https://**',   }})

封装 wx.request
在小程序目录下建立 api 文件夹,并在文件夹下创建 api.js 脚本。下面开始封装 wx.request

const app = getApp()const request = (url, options) = {   return new Promise((resolve, reject) = {       wx.request({           url: `${app.globalData.host}${url}`,           method: options.method,           data: options.method === 'GET' ? options.data : JSON.stringify(options.data),           header: {               'Content-Type': 'application/json; charset=UTF-8',               'x-token': 'x-token'  // 看自己是否需要           },           success(request) {               if (request.data.code === 2000) {                   resolve(request.data)               } else {                   reject(request.data)               }           },           fail(error) {               reject(error.data)           }       })   })}const get = (url, options = {}) = {   return request(url, { method: 'GET', data: options })}const post = (url, options) = {   return request(url, { method: 'POST', data: options })}const put = (url, options) = {   return request(url, { method: 'PUT', data: options })}// 不能声明DELETE(关键字)const remove = (url, options) = {   return request(url, { method: 'DELETE', data: options })}module.exports = {   get,   post,   put,   remove}

有个问题 get请求回来的数据怎样才能拿到 ,不然页面上的数据怎么显示,原文没说,我还是个菜鸟

,

管理 api 接口
项目中的 api 大部分都是可以复用的。为了后期方便维护管理,这个时候需要把 api 提出来。有多种方法,比如可以按模块建立相应的 js 脚本。如下:

const login = '/user/login' // 登录module.exports = {    login}

使用封装过后的 api

import api from '../api/api'import { login } from '../**/conf' // 链接注意填写正确 api.post(login, {    data: ''}).then(res = {    if(){}}).catch(err = {    wx.showToast({        title: err.message,        icon: 'none'    })})

post 请求就是api.post()…,get 请求就是api.get()…

感谢浏览微信小程序 wx.request 封装,欢迎评论指正,转载请标明出处

转载于博客园 点击跳转

TAG标签: 微信小程序链接前缀

http://www.xiaochengxub.com/read-105900.html