koa2快速入门

在前篇的基础上继续操作

分离Router

安装koa-router模块

npm install koa-router -save

/website/testPro目录下创建router.js文件

const router = require('koa-router')();
module.exports = (app) => {
    router.get('/',async(ctx,next) => {//根目录get请求
        ctx.response.body = '<h1>index page</h1>';
    });

    router.get('/home',async(ctx,next) => {
        console.log(ctx.request.query);
        console.log(ctx.request.querystring);
        ctx.response.body = `<h1>home page</h1>`;
    });
    router.get('/home/:id/:name',async(ctx,next) => {//指定参数的get请求
        console.log(ctx.params);
        ctx.response.body = `<h1>home page /:id/:name</h1>`;
    });

    app.use(router.routes()).use(router.allowedMethods());

}

index.js中引入router.js,代码如下:

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


//引入router.js

const router = require('./router');
router(app);

app.listen(3000,() =>{
    console.log('server is running at http://localhost:3000');
});

浏览器输入http://localhost:3000/homehttp://localhost:3000/home/1/tom 查看效果

分离controller
先安装koa-body模块,用于处理post提交

npm install koa-body -save

修改index.js文件,代码如下:

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

//用于处理post提交
const body = require('koa-body')();
app.use(body);

//引入router.js

const router = require('./router');
router(app);

app.listen(3000,() =>{
    console.log('server is running at http://localhost:3000');
});

在/website/testPro目录下新增controller文件夹,再添加home.js文件,代码如下:

module.exports = {
    index:async(ctx,next) => {
        ctx.response.body = '<h1>index page</h1>';
    },
    home:async(ctx,next) => {
        console.log(ctx.request.query);
        console.log(ctx.request.querystring);
        ctx.response.body = '<h1>home page</h1>';
    },
    login:async(ctx,next) => {
        if(ctx.method === 'GET'){
            ctx.response.body = `<form action="/user/login" method="post">
            账号:<input name ="username" type="text"/>
            <br/>
            密码:<input name="password" type="text" />
            <br/>
            <button type="submit">登录</button>
            </form>`;
        }else{
            let {username,password} = ctx.request.body;
            if(username == 'admin' && password == '12345'){
                ctx.response.body = 'login success';
            }else{
                ctx.response.body = 'login fail';
            }
        }
    },
}

需要修改router.js文件,在文件中引入controller/home.js,并以home.js中的函数作为HTTP请求的响应函数,代码如下:

const router = require('koa-router')();
//引入
const HomeController = require('./controller/home');
module.exports = (app) => {
    //只允许get
    router.get('/',HomeController.index);
    router.get('/home',HomeController.home);
    //允许get和post
    router.get('/user/login',HomeController.login);
    router.post('/user/login',HomeController.login);

    app.use(router.routes()).use(router.allowedMethods());

}

浏览器输入http://localhost:3000/user/login 查看效果

分离view

这里使用ejs模版

npm install koa-views --save
npm install ejs --save

修改/website/testPro/index.js,代码如下

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

//用于处理post提交
const body = require('koa-body')();
app.use(body);

//koa-views需要在路由引入之前引入
const views = require('koa-views');
//指定视图的文件夹为views,模版引擎使用ejs
app.use(views('views',{extension:'ejs'}));

//引入router.js
const router = require('./router');
router(app);


app.listen(3000,() =>{
    console.log('server is running at http://localhost:3000');
});

需要注意的是koa-views要在路由引入之前引入

修改/website/testPro/controller/home.js的index方法,代码如下

    index:async(ctx,next) => {
        //ctx.response.body = '<h1>index page</h1>';
        let title = 'index page by ejs';
        await ctx.render('index',{title});
    },

/website/testPro目录下添加views文件夹并创建index.ejs视图文件,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <h1><%= title %></h1>
</body>
</html>

用浏览器打开http://localhost:3000/ 即可看到效果

处理静态资源

npm install koa-static --save

修改/website/testPro/index.js,代码如下

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

//用于处理post提交
const body = require('koa-body')();
app.use(body);

//koa-views需要在路由引入之前引入
const views = require('koa-views');
//指定视图的文件夹为views,模版引擎使用ejs
app.use(views('views',{extension:'ejs'}));

const static = require('koa-static');
//配置静态资源目录为web
app.use(static('web'));

//引入router.js
const router = require('./router');
router(app);


app.listen(3000,() =>{
    console.log('server is running at http://localhost:3000');
});

/website/testPro目录下添加web文件夹并放置一张名为test.png的图片,修改index.ejs视图文件,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <h1><%= title %></h1>
    <img src="test.png" alt="">
</body>
</html>

浏览器刷新http://localhost:3000/ 即可看到效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值