Github上有一个express风格的koa脚手架,用着挺方便,一直以来使用koa开发web项目用的也都是那个脚手架,今天想自己从头搭一个web项目,就折腾了一下
脚手架地址: https://github.com/17koa/koa-generator
初始化
使用 npm init 初始化一个nodejs项目
mkdir koa-demo cd koa-demo npm init
一直回车即可,创建好之后目录里会有一个 package.json 文件
安装依赖
npm install --save koa koa-body koa-logger koa-json-error koa-router koa-static koa-njk
配置
在根目录下创建 app.js 然后贴上下面代码,代码内有注释,很简单
// 引入依赖 const koa = require('koa'); const koa_body = require('koa-body'); const koa_json_error = require('koa-json-error'); const koa_logger = require('koa-logger'); const koa_static = require('koa-static'); const koa_njk = require('koa-njk'); const path = require('path'); // 初始化koa const app = new koa() // 引入路由配置文件,这个在下面说明 const routers = require('./routes/routers'); // 配置程序异常
路由
在根目录下创建 routes 文件夹
在 routes 文件夹内创建 index.js routers.js 文件
在 index.js 文件内添加如下代码
// 测试路由,
配置路由,在 routers.js 文件内配置路由
const router = require('koa-router')(); // route const index = require('./index'); router.get('/view', index.view); router.get('/index', index.index); router.get('/index:id', index.index); router.post('/index', index.index); router.get('/test_error', index.test_error); module.exports = router
静态文件
在根目录创建文件夹 static 添加 app.css 文件,写上下面代码
body { background-color: #eee; }
模板
在根目录创建文件夹 views 添加 index.njk 文件,写上下面代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <link rel="stylesheet" href="/app.css" rel="external nofollow" > </head> <body> Hello, ! <br> <ul> <!-- 使用自定义的过滤器 --> </ul> </body> </html>
启动
安装 nodemon
npm install -g nodemon
在根目录运行命令启动项目
nodemon app.js
测试
访问 http://localhost:3000/view/
访问 http://localhost:3000/index/ 可以看到输出的json
{ "body": {}, "query": {}, "params": {} }
访问 http://localhost:3000/index/?id=1
{ "body": {}, "query": { "id": "1" }, "params": {} }
访问 http://localhost:3000/index/1
{ "body": {}, "query": {}, "params": { "id": "1" } }
POST 请求 curl -X POST http://localhost:3000/index/ -d '{"id": "1"}' -H 'Content-Type:application/json'
{ "body":{ "id":"1" }, "query":{}, "params":{} }
访问 http://localhost:3000/test_error
{ "code": 500, "description": "测试异常" }