1. dependencies

"co-mysql": "^1.0.0",
"koa": "^2.7.0",
"koa-better-body": "^3.0.4",
"koa-ejs": "^4.2.0",
"koa-router": "^7.4.0",
"koa-session": "^5.12.0",
"koa-static": "^5.0.0",
"mysql": "^2.17.1"

2. 主服务

引包

 const fs = require('fs');
const path = require('path');
const Koa = require('koa');
const Router = require('koa-router');
const session = require('koa-session');
const ejs = require('koa-ejs');
const body = require('koa-better-body'); const _static = require('./routers/static');
const config = require('./config'); const app = new Koa();
const router = new Router();

错误处理

 router.all('*', async (ctx, next) => { // * 表示所有的请求,都会经过这里的处理
try {
await next();
} catch (e) {
ctx.throw(500, e);
}
});

服务端渲染 koa-ejs

 ejs(app, {
root: path.resolve(__dirname, 'template'), // 模版路劲
layout: false, // 使用 render 方法渲染模版时有所区别,如果省略,会去找 template/layout.ejs
             // false: ctx.render('admin/index.ejs') 'abc': ctx.render('abc/admin/index.ejs')
viewExt: 'ejs',// 模版后缀名
cache: false, // 缓存
debug: false // 如果是 true,会把编译之后的内容全部输出
});

路由 koa-router

 router.use('/admin', require('./routers/admin')); // localhost:8080/admin/xxx
router.use('/api', require('./routers/api')); // localhost:8080/api/xxx
router.use('', require('./routers/www')); // '' 表示根,localhost:8080/xxx

开放静态资源 koa-static

_static(router, {
imageMaxAge: config.imageMaxAge,
scriptMaxAge: config.scriptMaxAge,
styleMaxAge: config.styleMaxAge,
htmlMaxAge: config.htmlMaxAge,
otherMaxAge: config.otherMaxAge
});
/*
  // 上面只是封装了, 比如
  // ...
  const static = require('koa-static');
  // ...
  router.all(/\.jsx?/i, static(path, options));
*/

session koa-session

1. .keys 文件是通过脚本生成的用来 session 签名的密钥,数组,每个元素都是无规律的不同字符组合

2. 这里可以使用同步读取文件的方式,因为是在启动服务的时候,只读取一次,所以,不会影响服务器性能

 app.keys = fs.readFileSync('.keys').toString().split('\r\n');
app.use(session({
maxAge: 20 * 60 * 1000, // 缓存时间 20 分钟
renew: true // 自动续期
}, app));

处理 POST 数据 koa-better-body

 app.use(body({
uploadDir: config.UPLOAD_DIR
}));

数据库 mysql co-mysql

1 app.context.db = require('./libs/database'); // app.context 相当于 ctx 的原型,所以,可以使用 ctx.db.query(sql语句) 来操作数据库

配置

1. 很多地方都需要 config,直接加到 app.context 上,通过 ctx.config 使用

 app.context.config = config;
 app.listen(config.HTTP_PORT, () => console.log(`Server running on ${config.HTTP_PORT}...`));
app.use(router.routes());

3. 数据库

 const mysql = require('mysql');
const co = require('co-mysql'); const config = require('../config'); const conn = mysql.createPool({
host: config.DB_HOST,
user: config.DB_USER,
password: config.DB_PASS,
port: config.DB_PORT,
database: config.DB_NAME
}); module.exports = co(conn);

4. md5

 const crypto = require('crypto');
const config = require('../config'); module.exports = {
// 生成 md5 值
md5 (buffer) {
const obj = crypto.createHash('md5');
obj.update(buffer + config.MD5_KEYS);
return obj.digest('hex');
}
};

Koa搭建简单服务器的更多相关文章

  1. Node安装及搭建简单服务器

    注:本文安装系统为mac,windows及其他系统下载对应安装包 ,mac下载后的安装包为apk文件,windows为msi文件. 安装 1.在网上下载node安装包,官方网站2.双击下载文件,按步骤 ...

  2. 利用gulp搭建简单服务器,gulp标准版

    var gulp = require('gulp'), autoprefixer = require('gulp-autoprefixer'), //自动添加css前缀 rename = requir ...

  3. nodeJs搭建简单服务器

    实现简单的例子:hello word 把第一个文件命名为server.js 在server.js里写入 var http  = require("http"); http.crea ...

  4. python3+socket搭建简易服务器

    踩了一上午的坑之后,终于对网络编程有了一点大致的.基本的了解.真的是0基础,之前对socket网络编程一点都不知道.(感觉自己与时代脱轨....) 首先我想对这些美妙的专业术语进行一番搜索: 服务器: ...

  5. 使用 Nodejs 搭建简单的Web服务器

    使用Nodejs搭建Web服务器是学习Node.js比较全面的入门教程,因为要完成一个简单的Web服务器,你需要学习Nodejs中几个比较重要的模块,比如:http协议模块.文件系统.url解析模块. ...

  6. Ubuntu 14.04搭建简单git服务器

    /****************************************************************************** * Ubuntu 14.04搭建简单gi ...

  7. mongoDB介绍、安装、搭建简单的mongoDB服务器(一)

    相关网站 1. http://www.mongodb.org/ 官网,可以下载安装程序,和doc,和驱动等. 2. http://www.mongoing.com/ 国内官方网站,博客,问题谈论等  ...

  8. 【netty】(2)---搭建一个简单服务器

    netty(2)---搭建一个简单服务器 说明:本篇博客是基于学习慕课网有关视频教学.效果:当用户访问:localhost:8088 后 服务器返回 "hello netty"; ...

  9. 总结一下搭建简单Web服务器的一些方法

    使用nodejs+anywhere模块搭建静态文件服务器 anywhere随时随地将你的当前目录变成一个静态文件服务器的根目录. 安装npm install anywhere -g,然后进入任意目录在 ...

随机推荐

  1. spring-cloud-zuul跨域问题解决

    问题发现 正常情况下,跨域是这样的: 1. 微服务配置跨域+zuul不配置=有跨域问题 2. 微服务配置+zuul配置=有跨域问题 3. 微服务不配置+zuul不配置=有跨域问题 4. 微服务不配置+ ...

  2. 在Struts2里面嵌入Spring

    第一步:在web.xml中增加以下的listener <listener> <listener-class>org.springframework.web.context.Co ...

  3. Silverlight 2.5D RPG游戏技巧与特效处理:(五)HLSL渲染动画

    原文:Silverlight 2.5D RPG游戏技巧与特效处理:(五)HLSL渲染动画 或许大家依旧对上一节中的“黑夜”及“梦回过去”记忆犹新,追问下去HLSL到底是何方神圣能实现如此炫酷之效果?层 ...

  4. AtCoder Regular Contest 084 C - Snuke Festival【二分】

    C - Snuke Festival ....最后想到了,可是不应该枚举a[],这样要二重循环,而应该枚举b[],这样只需一重循环... #include<iostream> #inclu ...

  5. xcode禁用代码分析的警告和内存泄漏

    在使用xcode进行iphone应用开发时,经常需要添加一些第三方的类库,而一些第三方的类库由于缺少维护,从而导致类库中含有各种警告和各种内存泄漏,但并不影响运行. 倘若我们需要用到第三方库,而由不想 ...

  6. Plupload的上传机制

    plupload支持多文件上传.经过测试发现,plupload在上传多个文件时,会把多个文件拆分成单个的一个一个上传.

  7. iphone 内存检测工具

    http://latest.docs.nimbuskit.info/NimbusOverview.html Nimbus Overview Sub-Modules Sensors Overview L ...

  8. 我钟爱的HTML5和CSS3在线工具【转】

    我真的喜欢上了HTML5, CSS3, JavaScript编程,但是有一些代码还是需要一些辅助工具来做才行,例如,CSS3的Gradient渐变如果手写代码的话真的不爽,还有像animation动画 ...

  9. epoll简介(一)

    一:概述   1:简介 EPOLL类似于POLL,是Linux特有的一种IO多路复用的机制.它在2.5.44内核中引入. 对于大量的描述符处理,EPOLL更有优势,它提供了三个系统调用来创建管理epo ...

  10. LInux下编译发生的libc相关错误

    在某主机上编译程序,发生有找不到libc的问题,自己写了个简单的hello world程序,编译也失败,报错如下: # gcc -o 1 1.c /usr/bin/ld: skipping incom ...