Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to generate Mini Program preview code

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

本篇内容主要讲解"小程序预览码怎么生成",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"小程序预览码怎么生成"吧!

撸起袖子从后端开始

为了省事,直接把前后端的东西放在一起。

先看看入口文件index.js,从这里我们可以知道后端要做两件事情,第一要能访问到前端build出来的静态资源,第二要能与前端通过HTTP接口进行交互。见代码:

const path = require('path')const Koa = require('koa')const koaStatic = require('koa-static')const bodyParser = require('koa-bodyparser')const router = require('./router')const app = new Koa()const port = 9871app.use(bodyParser())// 处理静态资源 这里是前端build好之后的目录app.use(koaStatic( path.resolve(__dirname, '../dist')))// 路由处理接口app.use(router.routes()).use(router.allowedMethods())// 监听端口app.listen(9871)console.log(`[demo] start-quick is starting at port ${port}`)

静态资源方面的话使用koa-static即可,重点是怎样给前端提供接口,这就要看路由了。

server/router/index.js

const Router = require('koa-router')// 业务逻辑const wx = require('../controller/wx')const router = new Router({ // 接口前缀 比如open接口 请求路径就是/api/open prefix: '/api'})router.get('/open', wx.open) .get('/login', wx.login) .get('/preview', wx.preview) .get('/build', wx.build)module.exports = router

这里可以清晰看到,后端提供了四个接口,但具体每个接口的业务逻辑则封装在controller里的wx.js,如果以后还有别的业务逻辑,就在controller加相应的模块即可。

server/controller/wx.js

// 微信开发者工具接口调用逻辑const {open, login, preview, build} = require('../utli/wxToolApi')// 处理成功失败返回格式的工具const {successBody, errorBody} = require('../utli')class WxController { /** * 根据环境对mpvue项目进行打包 * @returns {Promise} */ static async build (ctx) { // 前端传过来的get参数 const query = ctx.request.query if (!query || !query.env) { ctx.body = errorBody(null, '构建项目失败') return } const [err, data] = await build(query.env) ctx.body = err ? errorBody(err, '构建项目失败') : successBody(data, '构建项目成功') } /** * 打开微信开发者工具 * @returns {Promise} */ static async open (ctx) { const [err, data] = await open() ctx.body = err ? errorBody(err, '打开微信开发者工具失败') : successBody(data, '打开微信开发者工具成功') } /** * 登录微信开发者工具 * @returns {Promise} */ static async login (ctx) { const [err, data] = await login() ctx.body = err ? errorBody(err, '登录二维码返回失败') : successBody(data, '登录二维码返回成功') } /** * 查看预览码 * @returns {Promise} */ static async preview (ctx) { const [err, data] = await preview() ctx.body = err ? errorBody(err, '预览二维码返回失败') : successBody(data, '预览二维码返回成功') }}module.exports = WxController

为了代码更加清晰,这里将具体操作微信开发者工具的接口逻辑抽到util/wxToolApi.js里去了,仅仅处理怎样以统一格式返回给前端。util/wxToolApi.js

const {promiseWrap, successBody, errorBody} = require('../utli')const {INSTALL_PATH, PROJECT_PATH, PORT_PATH, PORT_FILE_NAME, HOST} = require('../const')const {readFile} = require('../utli/nodeApi')const shell = require('shelljs')const axios = require('axios')module.exports = { /** * 根据环境对mpvue项目进行打包 * @param env [doc, pre, prd] * @returns {*} */ build (env) { return promiseWrap(new Promise((resolve, reject) => { // 进入项目目录 shell.cd(PROJECT_PATH) // 执行打包命令 shell.exec(`npm run build:${env}`, function (code, stdout, stderr) { resolve(stdout) }) })) }, /** * 打开微信开发者工具 * @returns {*} */ open () { return promiseWrap(new Promise((resolve, reject) => { // 进入项目目录 shell.cd(INSTALL_PATH) // 执行微信开发者工具接口"命令行启动工具" shell.exec(`cli -o ${PROJECT_PATH}`, function (code, stdout, stderr) { if (stderr) return reject(stderr) resolve(stdout) }) })) }, /** * 获取微信开发者工具端口号 * @returns {Promise} */ async getPort () { shell.cd(PORT_PATH) // http 服务在工具启动后自动开启,HTTP 服务端口号在用户目录下记录,可通过检查用户目录、检查用户目录下是否有端口文件及尝试连接来判断工具是否安装/启动。 const [err, data] = await readFile(PORT_FILE_NAME) return err ? errorBody(err, '读取端口号文件失败') : successBody(data, '读取端口号文件成功') }, /** * 微信开发者工具进行登录 * @returns {*} */ login () { return promiseWrap(new Promise(async (resolve, reject) => { // 获取端口号 const portData = await module.exports.getPort() if (portData.code !== 0) { reject(portData) return } const port = portData.data axios.get(`http://${HOST}:${port}/login?format=base64`) .then(res => { resolve(res.data) }) .catch(e => { reject(e) }) })) }, /** * 微信开发者工具获取预览码 * @returns {*} */ preview () { return promiseWrap(new Promise(async (resolve, reject) => { const portData = await module.exports.getPort() if (portData.code !== 0) { reject(portData) return } const port = portData.data axios.get(`http://${HOST}:${port}/preview?format=base64&projectpath=${encodeURIComponent(PROJECT_PATH)}`) .then(res => { resolve(res.data) }) .catch(e => { reject(e) }) })) }}

这里有一点需要注意,为什么只有open接口需要用命令行调用方式?那是因为HTTP调用方式必须加端口,比如open接口

# 打开工具http://127.0.0.1:端口号/open# 打开/刷新项目http://127.0.0.1:端口号/open?projectpath=项目全路径

如果你根本都没有打开微信开发者工具,在以下地方就会找不到端口:

端口号文件位置:macOS : ~/Library/Application Support/微信web开发者工具/Default/.ideWindows : ~/AppData/Local/微信web开发者工具/User Data/Default/.ide

所以作为一个全自动化打码工具,怎么可能还要自己去手动打开微信开发者工具呢!

前端

后端的东西基本就那么多,终于到前端了,前端十分简单,就不多说了:

点击预览 请先登录

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report