day23

1-使用 koa 搭建服务器

const koa = require('koa') ;
const app = new koa() ;

// 路由的请求
// context (ctx) 上下文 请求和响应都在里面
app.use(async (ctx)=>{
ctx.body = 'hello koa2' ;
})
app.listen(3000,()=>{
console.log('服务器已启动,3000端口监听中....') ;
})

2-如何配置 koa 路由

const koa = require('koa') ;
const Router = require('koa-router');
// 创建路由对象
var router = require('koa-router')() ;

const app = new koa() ;

// 路由请求
router.get('/index',(ctx)=>{
ctx.body = 'hello koa' ;
})
router.get('/list',ctx=>{
ctx.body = 'hello list' ;
})

// 启用路由
app.use(router.routes())
.use(router.allowedMethods())

app.listen(3000,()=>{
console.log('服务器已启动,3000端口监听中... ') ;
})

3-静态资源如何获取

const koa = require('koa') ;
const Router = require('koa-router');
// 创建路由对象
var router = require('koa-router')() ;
const static = require('koa-static') ;
const path = require('path') ;

const app = new koa() ;

// 获取静态资源
app.use(static(path.join(__dirname,'public'))) ;

 

// 启用路由
app.use(router.routes())
.use(router.allowedMethods())

app.listen(3000,()=>{
console.log('服务器已启动,3000端口监听中... ') ;
})

4-koa 如何使用模板引擎

const koa = require('koa') ;
// 创建路由对象
var router = require('koa-router')() ;
const render = require('koa-art-template') ;
const path = require('path') ;

const app = new koa() ;
render(app,{
root:path.join(__dirname,'views'),
extname:'.html',
debug:process.env.NODE_ENV !== 'production'
})

// 路由请求
router.get('/add',async (ctx) => {
let litter = "张三"
await ctx.render('index',{
litter
})
})

// 启用路由
app.use(router.routes())
.use(router.allowedMethods())

app.listen(3000,()=>{
console.log('服务器已启动,3000端口监听中... ') ;
})

posted @ 2021-03-07 22:05  heartru  阅读(47)  评论(0)    收藏  举报