打算开发一个小程序,因为前端 API 请求各种各样,所以打算找一款设计比较好的小程序进行参考。

1 litemall

star:17k
架构方式:
util.js 中封装小程序的 request
api.js 中定义api地址

  1. function request(url, data = {}, method = "GET") {
  2. return new Promise(function(resolve, reject) {
  3. wx.request({
  4. url: url,
  5. data: data,
  6. method: method,
  7. header: {
  8. 'Content-Type': 'application/json',
  9. 'X-Litemall-Token': wx.getStorageSync('token')
  10. },
  11. success: function(res) {
  12. if (res.statusCode == 200) {
  13. if (res.data.errno == 501) {
  14. // 清除登录相关内容
  15. try {
  16. wx.removeStorageSync('userInfo');
  17. wx.removeStorageSync('token');
  18. } catch (e) {
  19. // Do something when catch error
  20. }
  21. // 切换到登录页面
  22. wx.navigateTo({
  23. url: '/pages/auth/login/login'
  24. });
  25. } else {
  26. resolve(res.data);
  27. }
  28. } else {
  29. reject(res.errMsg);
  30. }
  31. },
  32. fail: function(err) {
  33. reject(err)
  34. }
  35. })
  36. });
  37. }
  1. var WxApiRoot = 'http://localhost:8080/wx/';
  2. module.exports = {
  3. IndexUrl: WxApiRoot + 'home/index', //首页数据接口
  4. AboutUrl: WxApiRoot + 'home/about', //介绍信息
  5. AuthLoginByWeixin: WxApiRoot + 'auth/login_by_weixin', //微信登录
  6. };

实际使用

  1. const util = require('../utils/util.js');
  2. const api = require('../config/api.js');
  3. util.request(api.AuthLoginByWeixin, {
  4. code: res.code,
  5. userInfo: userInfo
  6. }, 'POST').then(res => {
  7. if (res.errno === 0) {
  8. //存储用户信息
  9. wx.setStorageSync('userInfo', res.data.userInfo);
  10. wx.setStorageSync('token', res.data.token);
  11. resolve(res);
  12. } else {
  13. reject(res);
  14. }
  15. }).catch((err) => {
  16. reject(err);
  17. });
  18. }).catch((err) => {
  19. reject(err);
  20. })

好处:简单明了