小程序流動圖書館開發(fā)實例
流動圖書館是一個圖書漂流和借閱工具,旨在共享閑置圖書,并鏈接趣味相投的小伙伴。那么流動圖書館小程序如何開發(fā)
預覽
技術棧
小程序MINA框架: 一個響應的數據綁定框架。分為兩塊視圖層(View)和邏輯層(App Service)
Flex:flex彈性布局
Express: http服務框架
websocket: 前后端消息的實時推送
mongoose: 操作mongodb數據庫
pm2: 服務端使用pm2部署,常駐進程
代碼結構
微信小程序中每個頁面會有四個文件.js.json.wxml.wxss
js文件中是頁面的邏輯,json文件是頁面的一些配置,wxml是小程序的頁面結構,wxss為頁面的樣式。
封裝http請求
const request = (obj) => {
if(obj.header){
obj.header.sessionId = session.sessionId;
}else{
obj.header = { sessionId: session.sessionId};
}
wx.request(obj);
}
在請求頭中手動加上sessionId,因為小程序沒有cookie。
websocket
//連接websocket
wx.connectSocket({
url: 'wss://liudongtushuguan.cn/socket?sessionId=' + session.sessionId,
});
wx.onSocketOpen(function(res){
});
wx.onSocketClose(function(res){
console.log('websocket closed');
});
wx.onSocketMessage(function(res){ //收到消息的回調
let msg = JSON.parse(res.data);
let msgs = that.data.borrowMessage;
msgs.unshift(msg);
that.setData({ borrowMessage: msgs});
});
//發(fā)送socket消息
let data = JSON.stringify({
targetId: bookData.ownerId,
nickName: APP.globalData.userInfo.nickName,
bookName: bookData.title,
time: new Date().toLocaleString(),
bookId: bookId,
wxNum: wxNum,
phoneNum: phoneNum,
msg: msg,
});
wx.sendSocketMessage({
data: data,
});
服務端
代碼目錄
Express框架實現(xiàn)http服務
const https = require('https');
const fs = require('fs');
const express = require('express')
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
const queryString = require('querystring');
const URL = require('url');
const socket = require('./service/socket');
const router = require('./routes/router').router;
//獲取認證證書
var key = fs.readFileSync('./key/2_www.liudongtushuguan.cn.key');
var cert = fs.readFileSync('./key/1_www.liudongtushuguan.cn_bundle.crt');
var options = {
key : key,
cert : cert,
};
app.use(cookieParser());
app.use(bodyParser.json());
const httpsServer = https.createServer(options,app);
httpsServer.listen(443,() =>{
console.log('listening 443 port');
});
socket(httpsServer); //websocket
app.use(router);
小程序規(guī)定必須要用https協(xié)議。
websocket模塊
const WebSocket = require('ws'); //使用ws模塊
const queryString = require('querystring');
const URL = require('url');
const sessions = require('./session');
module.exports = (httpServer) => {
const wss = new WebSocket.Server({server : httpServer});
wss.on('connection',(ws, req) => {
let sessionId = queryString.parse(URL.parse(req.url).query).sessionId;
ws.id = sessionId;
ws.on('message' , (msg) => {
let msgObj = JSON.parse(msg);
if(sessions[msgObj.targetId]){
wss.clients.forEach((client) => {
if(client.id === msgObj.targetId){
let data = {
time : msgObj.time,
borrower :msgObj.nickName,
book :msgObj.bookName,
borrowerId : sessions[sessionId],
bookId : msgObj.bookId,
wxNum : msgObj.wxNum,
phoneNum : msgObj.phoneNum,
msg : msgObj.msg
};
client.send(JSON.stringify(data));
}
});
}
});
});
};
mongoose操作數據庫
db.js:
const mongoose = require('mongoose');
mongoose.connect('mongodb://app:12345678@127.0.0.1/wxapp');
const connection = mongoose.connection;
connection.once('open', (err) => {
if(err){
console.log('Database connection failure');
}else{
console.log('Database opened');
}
});
connection.on('error',(err) => {
console.log('Mongoose connected error '+ err);
});
connection.on('disconnected', () => {
console.log('Mongoose disconnected');
});
module.exports = {
connection : connection,
mongoose : mongoose,
};
model.js:
const Schema = mongoose.Schema;
const UserSchema = new Schema({
onlyId : {type: String},
publishedBooks : {type: Array},
borrowedBooks : {type: Array},
borrowMessages : Array,
});
const BookSchma = new Schema({
isbn : String,
title : String,
press : String,
author : String,
rate : String,
tags : String,
image : String,
status : {type : Boolean,default : true},
ownerId : String,
owner : String,
ownerImage : String,
});
const userModel = mongoose.model('user' , UserSchema);
const bookModel = mongoose.model('book' , BookSchma);
module.exports = {
UserModel : userModel,
BookModel : bookModel,
}
獲得微信用戶的openId
小程序前端會請求微信服務器得到一個code, 將code發(fā)送給自己的服務器,然后自己的服務器給微信服務器發(fā)送請求,得到微信用戶的唯一標識openId
const https = require('https');
const queryString = require('querystring');
const sessions = require('./session');
module.exports = (req, res, next) => {
let code = req.query.code;
let otherRes = res;
DATA.js_code = code;
OPTION.path = PATH + queryString.stringify(DATA);
let wxReq = https.request(OPTION, (res) => {
if(res.statusCode == 200){
let json = '';
res.on('data' , (data) => {
json+=data;
});
res.on('end' , () => {
json =JSON.parse(json);
let openId = json.openid;
sessions[openId] = openId;
otherRes.type('application/json');
otherRes.json({
data : {'sessionId' : openId},
});
otherRes.status(200);
});
}
});
wxReq.end();
};
使用pm2部署
安裝pm2
npm install -g pm2
啟動應用
pm2 start app.js
HiShop小程序工具提供多類型商城/門店小程序制作,可視化編輯 1秒生成5步上線。通過拖拽、拼接模塊布局小程序商城頁面,所看即所得,只需要美工就能做出精美商城。
更多小程序資訊,盡在:m.descansotropical.com/xiaocx/