2018-09-08第十五天课

2018-09-08  本文已影响0人  无欲而为

HTTP 监听客户端的请求 (地址和端口),默认端口是80
静态HTTP 服务器
koa 框架
更小,更精简,更健壮的框架

app.use(
    KoaStaticCache(__dirname + '/static',{
        // root:__dirname + '/static' //和上面的第一个参数效果一样
        prefix:'/public',//如果当前请求的的url 是以 '/public' 开始 ,则作为静态资源请求
    })
)


//定义在/user  上面的多个子路由: 用户首页和用户收货地址 
const userRouter = new Router();
router.use('/user', userRouter.routes());

userRouter.get('/',(ctx,next) => {
    ctx.body = '用户首页'
});

userRouter.get('/address',(ctx,next) => {
    ctx.body = '用户收货地址'
});

//把 路由对象挂载到app对象中   一定要写在最后面
app.use( router.routes());

//定义在/user  上面的多个子路由: 用户首页和用户收货地址 
const userRouter = new Router();
userRouter.get('/',(ctx,next) => {
    ctx.body = '用户首页'
});

userRouter.get('/address',(ctx,next) => {
    ctx.body = '用户收货地址'
});
router.use('/user', userRouter.routes());


const Koa = require('koa');//包装过的http
const Router = require('koa-router');
const Swig = require('koa-swig');
const co = require('co');

let users = [
    {username: 'mt'},
    {username: 'mt2'},
    {username: 'mt3'},
    {username: 'mt4'},
    {username: 'mt5'},
    {username: 'mt6'},
    {username: 'mt7'},
    {username: 'mt8'},
    {username: 'mt9'},
    {username: 'mt10'},
    {username: 'mt11'},
    {username: 'mt12'},
]


const app = new Koa();//创建 一个 Http 服务器 监听请求 等同于 http.createSsuperver
const router = new Router();



app.use(router.routes());


const render = Swig({
    root: __dirname + '/views',
    autoescape: true,
    cache: false,
    ext: '.html'
});
app.context.render = co.wrap(render);

router.get('/list', async (ctx, next) => {
    ctx.body = await ctx.render('list.html',{
        users
    });

});


app.listen(80);

<!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>Document</title>
</head>
<body>
    <h1> SKT T1 K - {{Math.random()}} </h1>
    <ul>
        {%for user in users%}
        <li>{{user.username}}</li>
        {%endfor%}
    </ul>
    
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读