2.小程序:后台提供接口前端获取接口数据

tech2022-07-17  166

后台过程详见:前端传入数字后台生成二维码,后台使用mockjs生成数据 一.后台的代码//详见:d:/style/node var qr = require('qr-image'); var fs = require('fs') var express = require('express') var app = express() var mock = require('mockjs') let typeList = mock.mock({ 'list|10': [ { 'id|+1': 1, name: "@cword(2,4)", } ] }) //模拟后台建接口 req请求消息 res响应消息 app.get('/typeList', (req, res) => { // let id = req.query.id//筛选数据:前端传入id后太筛选数据给前端 // if (id) userList = userList.find(r => r.id === id) res.json(typeList) }) //前端传入数据,后台添加 req请求消息 res响应消息 // app.get("/adduser", (req, res) => { // userList.push({ // id: req.query.id, // name: req.query.name, // city: req.query.city, // }) // res.json(true) // }) //启动接口 成功打印:"程序已启动" app.listen(8989, () => { console.log("程序已启动"); }).前端:详见小程序demo1 1.data里要有数组接收 data: { menu: [], } 2.需要引入utils/index,修改页面的开头 import Router from '../../utils/index' Router({ 3.在onLoad里面调用函数 /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.getTypeList() }, 4.编写函数:getTypeList async getTypeList() { let { list } = await this.$get('http://localhost:8989/typeList') this.$set('menu', list) }, 5.$get的来源 在utils下建立index.js,内代码: import qs from "qs" //引入qs function request(methods, url, data) { let start = +new Date() //.getTime return new Promise((resolve, reject) => { wx.showLoading({ //页面提示:加载中 title: '加载中', }) if (!url.startsWith('http')) url = "https://simbajs.com:996" + url wx.request({ methods, url, // url: "http://simbajs.com:89" + url, data, success: res => { //加载成功 console.log(`${methods}${url},参数是 ${qs.stringify(data)}耗时${+new Date - start}毫秒`); resolve(res.data) }, complete() { //加载完成,失败,成功都会走 wx.hideLoading({}) //关闭页面提示:加载中 console.log(`耗时${+new Date - start}毫秒`); } }) }) } export function $get(url, data) { return request("GET", url, data) } export function $post(url, data) { return request("POST", url, data) } export function $d(e, key) { let res = e.currentTarget.dataset return key ? res[key] : res } export function $msg(msg) { wx.showToast({ title: msg, icon: 'none' //不要图标 }) } export function $set(key, val) { this.setData({ [key]: val }) } export function $setVal(e) { let { key } = this.$d(e); this.$set(key, e.detail) } export function $confirm(title) { return new Promise((resolve, reject) => { wx.showModal({ title, success: (res) => { resolve(res.confirm) } }) }) } /** *统一页面对象,封装了Page,添加了自定义方法 *@param{*}option 同原本的Page参数 */ export default function Router(option) { option.$setVal = $setVal option.$get = $get option.$post = $post option.$d = $d option.$msg = $msg option.$set = $set option.$confirm = $confirm return Page(option) }
最新回复(0)