您好,登錄后才能下訂單哦!
本篇內容介紹了“小程序流動圖書館如何開發”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
小程序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});
});
//發送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框架實現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);
小程序規定必須要用https協議。
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發送給自己的服務器,然后自己的服務器給微信服務器發送請求,得到微信用戶的唯一標識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
“小程序流動圖書館如何開發”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。