npm init // 初始化package.jsonhtml
npm i koa // 安裝koa2前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello koa2</title> </head> <body> <h1>Hello Koa2!</h1> </body> </html>
const fs = require('fs'); const Koa = require('koa'); const app = new Koa(); app.use(async (ctx) => { // ctx.body = 'hello koa2' ctx.type = 'html'; ctx.body = fs.createReadStream('./views/template.html'); }); app.listen(1029); console.log('koa damo is starting at port 1029');
const Koa = require('koa'); const Router = require('koa-router'); let server = new Koa(); let router = new Router(); server.listen(8080); router.get('/a', async ctx=>{ ctx.body='aaaaa'; }); server.use(router.routes())
const Koa = require('koa'); const Router = require('koa-router'); let server = new Koa(); let router = new Router(); server.listen(8080); router.get('/a', async ctx=>{ ctx.body='aaaaa'; }); server.use(router.routes())Koa基礎結
二層路由 1.引入路由對象 2.建立路由 3.配置路由 4.對外使用node
const Router = require('koa-router'); // 嵌套二級 let home = new Router(); home.get('/',ctx=>{ ctx.body ='前端'; }); home.get('/login', async ctx=>{ ctx.body='login'; }); home.get('/sigin', async ctx=>{ ctx.body='sigin'; }); module.exports=home.routes();