小程序第四讲 网络请求

写在前面的话

上一篇我们讲到了vue的一些特性(wepy),这一讲我们围绕着网络请求进行讲解,以及网络请求的封装和使用,结合项目所用到的一些进行讲解,另外由于项目本身原有的接口服务都已经停止运行,这里我们找了一个网易严选的项目(基于thinkjs)的服务进行讲解和修改调整。这里附上服务项目的地址

上一篇我们提到了一些遗留问题:
在这里插入图片描述
现在我们开始填写第二个坑 替换原有api服务使用新的api服务

网络工具类封装

import wepy from 'wepy';
import util from './util';
import md5 from './md5';
import tip from './tip'

const API_SECRET_KEY = 'www.mall.cycle.com'
const TIMESTAMP = util.getCurrentTime()
const SIGN = md5.hex_md5((TIMESTAMP + API_SECRET_KEY).toLowerCase())

const wxRequest = async(params = {}, url) => {
    tip.loading();//加载开始
    let data = params.query || {};
    data.sign = SIGN;
    data.time = TIMESTAMP;
    let res = await wepy.request({
        url: url,
        method: params.method || 'GET',
        data: data,
        header: { 'Content-Type': 'application/json' },
    });
    tip.loaded();//加载完成
    console.log(res)
    return res.data;
};


module.exports = {
    wxRequest
}

网络工具使用

  1. 接口统一管理
import {
  wxRequest
} from '@/utils/wxRequest';

let env = "-test" //-dev 或者 -test

const apiMall = 'http://127.0.0.1:8360'

/**
 * 获取发现好商品接口
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
const getDiscoverList = (params) => wxRequest(params, apiMall + '/goods/list?cateidOne=1&cateidTwo=0&price=0&sales=2');

//查询广告列表
const getAdList = (params) => wxRequest(params, apiMall + '/api/adverts/list');

const getHomeData = (params) => wxRequest(params, apiMall + '/api/index');

export default {
  hostGoodsList,
  getDiscoverList,
  getHomeData
  }
  1. 接口调用

export default class Home extends wepy.page {
	async getHomeData () {
      const json = await api.getHomeData({method: 'GET'});
      console.log(JSON.stringify(json))
      if (json.errno == 0) {
        this.adList = json.data.banner;
        this.discoverList = json.data.hotGoodsList;
        this.$apply();
      } else {}
    }
}

结束语

真的很晚了,如果又不详细的地方还请见谅!
喜欢加个关注支持一下后续会有更多更新内容,我好困啊我要睡觉了

项目地址

https://github.com/crobotvip/smallshop.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值