nodejs之koa2 -- 路由

nodejs之koa2 – 路由

原生路由

网站都是有多个界面的,在函数内部通过 ctx.request.url 是可以获取到当前用户请求的路径的,由此我们可以实现简单的路由,
接着上一篇的代码接着往下写。

由于每次启动都要执行 node app.js,感觉不舒服,就把启动命令配置为了 npm start,在packafe.json中的scripts中添加下面一行就好了,

"start": "node app.js",

1.首先在views目录下新建一个about.html文件,内容如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>about</title>
</head>
<body>
    <h1>about</h1>
    <p>This is about pages.</p>
    <a href="/">这是 about.html,点击返回index.html</a>
</body>
</html>

2.将template.html重命名为 index.html 内容修改为

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello koa2</title>
</head>
<body>
    <h1>Hello Koa2!</h1>
    <p>这是经过模版渲染过来的文件!</p>
    <a href="/about">点击这里会进入 about.html</a>
</body>
</html>

3.然后我们根据 ctx.request.url 这个属性,进行路由的分配,app.js中的内容如下

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


app.use((ctx) => {
    // ctx.body = 'hello koa2'
    if(ctx.request.url == '/about'){
        ctx.type = 'html';
        ctx.body = fs.createReadStream('./views/about.html');
    }else{
        ctx.type = 'html';
        ctx.body = fs.createReadStream('./views/index.html');
    }
});

app.listen(1029);
console.log('koa project is starting at port 1029');

npm start 运行项目,点击a标签两个页面就回来回切换,成功。

koa-router 模块

原生的路由用起来不是很方便,我们可以使用封装好的koa-router模块,运行下面的命令安装koa-router

npm i koa-router –save

然后将app.js修改为如下

const fs = require('fs');
// 引入koa-router
const Router = require('koa-router');
const Koa = require('koa');
const app = new Koa();
const router = new Router();

// 原生实现路由
/* app.use((ctx) => {
    if(ctx.request.url == '/about'){
        ctx.type = 'html';
        ctx.body = fs.createReadStream('./views/about.html');
    }else{
        ctx.type = 'html';
        ctx.body = fs.createReadStream('./views/index.html');
    }
}); */

// koa-router 中间件
router.get('/',async (ctx,next) => {
    ctx.type = 'html';
    ctx.body = fs.createReadStream('./views/index.html');
});
router.get('/about',async (ctx,next) => {
    ctx.type = 'html';
    ctx.body = fs.createReadStream('./views/about.html');
});

// 将 router 挂载到app上
app.use(router.routes());

app.listen(1029);
console.log('koa project is starting at port 1029');

运行项目,和原生一样的效果,代码看上去要清晰的多。

至此,简单的路由已经完成,可以愉快的写代码了,下一篇,小弟就记录一下koa的数据请求获取。

本文纯手打,有不当之处请留言!如果对小伙伴们有帮助的话,点赞啊,谢谢!

当然可以。以下是使用Node.js和Koa2构建RESTful API服务器的基本步骤: 首先,确保已经安装了Node.js并在终端中创建一个新的项目目录,例如`koa_api_server`。然后,初始化项目并安装必要的依赖: ```bash mkdir koa_api_server cd koa_api_server npm init -y npm install koa koa-router body-parser ``` 接着,创建两个文件:`index.js`作为主入口文件,`routes.js`负责定义API路由。 **index.js** ```javascript // 引入所需模块 const Koa = require('koa'); const app = new Koa(); const Router = require('koa-router'); const bodyParser = require('body-parser'); const cors = require('cors'); // 添加跨域支持 // 初始化中间件 app.use(bodyParser.json()); app.use(cors()); // 允许跨域请求 // 加载路由 const routes = require('./routes'); routes(app); // 将路由挂载到应用上 // 设置错误处理 app.on('error', err => { console.error('Error occurred:', err); }); // 启动服务器 const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is listening on port ${port}`); }); ``` **routes.js** ```javascript // 导出一个函数来添加路由 exports = module.exports = function (app) { // 创建路由器 const router = new Router(); // GET 请求示例:获取所有用户 router.get('/users', async ctx => { // 想象这是从数据库获取的数据 let users = [{ id: 1, name: 'User1' }, { id: 2, name: 'User2' }]; ctx.body = users; ctx.status = 200; }); // POST 请求示例:创建新的用户 router.post('/users', async ctx => { const newUser = ctx.request.body; // 对用户数据进行验证或存入数据库 if (!newUser.name || !newUser.email) { return ctx.throw(400, 'Invalid user data'); } ctx.body = { id: Date.now(), ...newUser }; ctx.status = 201; }); // 使用app.use()添加路由到应用 app.use(router.routes(), router.allowedMethods()); }; ``` 这个简单的例子包括了基本的GET和POST请求,以及跨域支持。为了持久运行,你可能还需要添加日志记录和错误处理功能。记得根据项目需求对路由进行相应的扩展和错误处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值