之前一直用的express,当作本地服务器测试使用,最近发现使用koa的同学比较多,就差看文档学习了一下,直接贴项目了.项目目录下运行指令
npm install
npm start
-
项目目录
├── index.js ├── package-lock.json ├── package.json ├── public │ ├── css │ │ ├── style.css │ │ └── style1.css │ ├── index.html │ └── ts │ └── main.ts └── -
Index.js
const Koa = require('koa'); const app = new Koa(); const route = require('koa-route'); const serve = require('koa-static'); const path = require('path'); // 把静态页统一放到public中管理 const home = serve(path.join(__dirname)+'/public/'); // hello接口 const hello = ctx => { ctx.response.body = 'Hello World'; }; // route 测试 app.use(home); app.use(route.get('/hello', hello)); app.listen(3000,function(){ console.log('server is running on port 3000') }); -
package.json
{ "name": "koaserver", "version": "1.0.0", "description": "koa 搭建server服务器 ", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" }, "author": "", "license": "ISC", "dependencies": { "koa": "2.13.0", "koa-route": "3.2.0", "koa-static": "5.0.0", "path": "0.12.7" } }