koa2 的介绍
Koa 是一个新的 web 框架, 由 Express 幕后的原班人马打造, 致力于成为 Web 应用和 API 开发领域中的一个更小, 更富有表现力, 更健壮的基石. 通过利用 async 函数, Koa 帮你丢弃回调函数, 并有力地增强错误处理. Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法, 帮助您快速而愉快地编写服务端应用程序.
koa2 安装
- NPM install koa
- koa middleware
每收到一个 http 请求, koa 就会调用通过 App.use()注册的 async 函数, 并传入 ctx 和 next 参数
middleware 的顺序很重要, 也就是调用 App.use()的顺序决定了 middleware 的顺序
对于 await next(), 如果一个 middleware 没有调用, 则后续的 middleware 将不再执行了, 使用场景
如, 一个检测用户权限的 middleware 可以决定是否继续处理请求, 还是直接返回 403 错误
- App.use(async (ctx, next) => {
- if (await checkUserPermission(ctx)) {
- await next();
- } else {
- ctx.response.status = 403;
- }
- });
ctx 简写
ctx.url 相当于 ctx.request.url,ctx.type 相当于 ctx.response.type
url 处理 , 使用 koa-router
安装 koa-router
- NPM install koa-router
- // 注意 require('koa-router')返回的是函数:
- const router = require('koa-router')();
这里导入 koa-router 的语句最后的 () 是函数调用
const router = require('koa-router')();
相当于
- const fn_router = require('koa-router');
- const router = fn_router();
- // add url-route:
- router.get('/hello/:name', async (ctx, next) => {
- var name = ctx.params.name;
- ctx.response.body = `<h1>Hello, ${name}!</h1>`;
- });
- router.get('/', async (ctx, next) => {
- ctx.response.body = '<h1>Index</h1>';
- });
- // add router middleware:
- App.use(router.routes());
这样我们在访问 http://localhost:3000/hello/kerry 时会打印 hello,kerry
处理 post 请求
post 请求通常会发送一个表单, 或者 JSON, 它作为 request 的 body 发送, 但无论是 Node.JS 提供的原始 request 对象, 还是 koa 提供的 request 对象, 都不提供解析 request 的 body 的功能, 所以我们需要用到 koa-bodyparser 中间件来解析 request 的 body
安装 koa-bodyparser
- NPM install koa-bodyparser
- const bodyParser = require('koa-bodyparser');
- // 解决 body 需在 router 之前注册到 App 对象上
- App.use(bodyParser());
这样我们就可以处理 post 请求了
- router.get('/', async (ctx, next) => {
- ctx.response.body = `<h1>Index</h1>
- <form action="/signin" method="post">
- <p>Name: <input name="name" value="koa"></p>
- <p>Password: <input name="password" type="password"></p>
- <p><input type="submit" value="Submit"></p>
- </form>`;
- });
- router.post('/signin', async (ctx, next) => {
- var
- name = ctx.request.body.name || '',
- password = ctx.request.body.password || '';
- console.log(`signin with name: ${name}, password: ${password}`);
- if (name === 'koa' && password === '12345') {
- ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
- } else {
- ctx.response.body = `<h1>Login failed!</h1>
- <p><a href="/">Try again</a></p>`;
- }
- });
代码优化
所有的代码都放在了 App.JS 中
我们可以单独将所有路由放到一个 JS 文件中, 如果是复杂系统, 还可以按模块建立多个路由文件, 如
user.JS(处理用户管理相关 url),login.JS(处理用户登录相关 url)
静态资源
安装 koa-static
- NPM install koa-static
- const static = require('koa-static')
- const path = require('path')
- // 静态资源目录
- App.use(static(
- path.join( __dirname,'./static')
- ));
我们在根目录下建立 static 文件夹, 新建一个 JSON 文件, 输入如下地址访问
http://localhost:3000/china.geojson
art-template 模板引擎
- NPM install --save art-template
- NPM install --save koa-art-template
- // 模板引擎
- const render = require('koa-art-template');
- render(App, {
- root: path.join(__dirname, './static'),
- extname: '.html',
- // debug: process.env.NODE_ENV !== 'production'
- });
- // 使用 ctx.render 渲染页面 可传递数据
- router.get('/user', async (ctx, next) => {
- ctx.render('user',{
- data:'hello msg'
- });
- });
HTML 中渲染数据 {{data}}
更多用法查看
koa2 跨域请求设置
- https://github.com/zadzbw/koa2-cors
- NPM install --save koa2-cors
- var cors = require('koa2-cors');
- App.use(cors());
开发部署 , 使用 nodemon 在本地开发环境下自动重启项目
1, 项目搭建好后, 通过 node 运行
node App.JS
也可以在 package.JSON 中添加 scripts
- "scripts": {
- "start": "node app.js"
- }
这样就可以运行
NPM run start
然后访问 http://localhost:3000
2, 通过 nodemon 来运行项目
NPM install -g nodemon
之后用 nodemon 来代替 node 来启动应用
nodemon App.JS
3, 如果是在线上 我们则使用 pm2 来管理应用程序,
pm2 是一个带有负载均衡功能的 Node 应用的进程管理器. 当你要把你的独立代码利用全部的服务器上的所有 CPU, 并保证进程永远都活着, 0 秒的重载, PM2 是完美的
https://www.cnblogs.com/lxg0/p/7771229.html
最后
通过以上简单介绍对 koa2 使用, 我搭建了一个 koa2 本地静态 node 服务器, 已上传至 GitHub, 欢迎大家 star 或 clone
https://github.com/fozero/koa2-server
来源: https://www.cnblogs.com/fozero/p/10171322.html