使用egg.js中间件验证用户请求
中间件在计算机软件系统应用中用途非常广泛,一般用来拦截请求,从而进行前置或者后置处理,例如安全校验、合法请求判断和用户身份验证等。本文将演示如何在egg.js框架中使用中间件来验证用户的请求是否正确。
中间件在计算机软件系统应用中用途非常广泛,一般用来拦截请求,从而进行前置或者后置处理,例如安全校验、合法请求判断和用户身份验证等。本文将演示如何在egg.js框架中使用中间件来验证用户的请求是否正确。
编写user方法并通过中间件验证请求
在编写user方法时,我们可以通过中间件来验证请求是否合法。以下是一个示例代码:
// app/controller/home.js
'use strict';
const { Controller } require('egg');
class HomeController extends Controller {
async index() {
const { ctx } this;
'hi, eggjs!';
}
// 用户个人中心
async user() {
const { ctx } this;
'hi, welcome user center!';
}
}
module.exports HomeController;
编写check中间件
接下来,我们需要编写一个名为check的中间件来检查请求的合法性。以下是示例代码:
// app/middleware/check.js
'use strict';
module.exports options gt; {
return async function check(ctx, next) {
// 获取url传来的token参数
const token ;
const sys_token 'test'; // 假设系统存储的token
// 判断token是否合法
if(sys_token ! token) {
401;
return { code: 'error', msg: 'token无效' };
}
// 放行
await next();
}
}
引入中间件并设置路由
在路由中,我们需要引入check中间件,并使用它来验证请求的合法性。以下是示例代码:
// app/router.js
'use strict';
/
* @param {} app - egg application
*/
module.exports app gt; {
const { router, controller } app;
// 中间件
const ck ();
('/index', );
// 访问用户中心,中间件验证token是否合法
('/userinfo', ck, );
}
现在,可以启动项目并测试中间件的功能了。
启动项目
打开命令终端,切换至项目根目录,并执行以下命令启动项目:
npm run dev
验证中间件
打开浏览器,在地址栏输入以下URL进行中间件验证的测试:
- 错误的token:http://127.0.0.1:7001/userinfo?tokentt2023
- 正确的token:http://127.0.0.1:7001/userinfo?tokentest
根据测试结果,如果token无效,则会提示"token无效";而如果token有效,则成功进入个人中心页面。通过封装业务逻辑成中间件的方式,可以使代码更简洁且具有更强的扩展性。