写在前面
本人自身就是一个乒乓球爱好者, 但是由于工作之后, 小伙伴都比较忙, 没有一定的时间相约打球, 于是最近准备写一个约乒乓球的小程序, 然后写后端的接口代码, 数据库的搭建, 并项目部署到服务器中去.
小程序码
<img src="https://user-gold-cdn.xitu.io/2018/5/6/1633328a72242335?w=344&h=344&f=jpeg&s=65975" https://user-gold-cdn.xitu.io/2018/5/6/1633328a72242335?w=344&h=344&f=jpeg&s=65975%22 ; width="150px">
小程序的技术选型
在小程序这一块, 也出现了好几种方案, 有微信官方到写法, 有参考 vue 写法的 wepy 架子, 也有美团出品, 把 vue 编译成小程序的 mpvue, 尝试过 wepy 的写法后, 我最后还是使用了官方的写法, 然后加入了 promise, async/await 的写法.
- return new Promise((resolve, reject) => {
- obj.success = function (res) {
- resolve(res)
- }
- obj.fail = function (res) {
- reject(res)
- }
- })
- async onLoad (options) {
- const { data } = await GetActiveList()
- this.setData({
- activeList: data
- })
- }
Node 框架选型
参考的方案有 Hapi,Egg,Express,Koa, 目前采取的是阿里 "企业级的开发方案"Egg 作为后端的技术方案
数据库
myqsl/moogdb
服务器
目前部署在阿里云上
1. 安装开发环境
基于 node 8.9.4
$ npm install express-generator -g
$ express myapp
2. 路由
- var http = require('http');
- var express = require('express');
- const querystring = require('querystring');
- var router = express.Router();
- var request = require('../utils/request');
- /**
- * 获取活动列表
- * @param {} '/api/getActiveList'
- * @param {} function(req
- * @param {} res
- * @param {} next
- */
- router.post('/api/getActiveList', function(req, res, next) {
- const postData = querystring.stringify(req.body);
- request.post(req, res, postData, '/app/mock/3317/getActiveList')
- });
3. 封装请求
- var http = require('http');
- exports.post = function(req, res, data, path){
- const options = {
- hostname: 'rap2api.taobao.org',
- port: 80,
- path: path,
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'Content-Length': Buffer.byteLength(data)
- }
- };
- const proxyHttp = http.request(options, (response) => {
- console.log(` 状态码: ${response.statusCode}`);
- console.log(` 响应头: ${JSON.stringify(response.headers)}`);
- response.setEncoding('utf8');
- response.on('data', (chunk) => {
- console.log(` 响应主体: ${chunk}`);
- });
- response.pipe(res)
- response.on('end', () => {
- console.log('响应中已无数据.');
- });
- });
- proxyHttp.on('error', (e) => {
- console.error(` 请求遇到问题: ${e.message}`);
- });
- // 写入数据到请求主体
- proxyHttp.write(data);
- proxyHttp.end();
- }
守护者 PM2
1. 安装 pm2
$ npm install pm2 -g
2. 启动项目
$ pm2 start /bin/www
Start an app using all CPUs available + set a name :
$ pm2 start app.js -i 0 --name "api"
3. 更多 pm2 命令
$ pm2 -h
目前项目进度
后端的数据支撑来自阿里 rap 模拟数据, 本人因为只是一个小前端, 对数据库的知识还需要补充, 后续会把真实的数据接入到项目中.
项目地址
一起乒 https://github.com/FuYiwei/WeChatAboutTheBall
一起乒 wepy https://github.com/FuYiwei/WeChatAboutTheBall-Wepy
一起乒 node https://github.com/FuYiwei/WeApp-TheBall-Node
来源: http://www.qdfuns.com/article/50154/7d9c191d929bf3f80bc50cbf804b5b3d.html