node.js - 如何将 use() 的实例应用于除 app.use(express.static("dist")) 传递的路由之外的所有路由?
问题描述
我想我在写它的过程中已经解决了这个问题,基本上解决方案似乎是:
将静态文件处理程序移到 use() 的另一个实例之上
确认这是一种可接受的方法将不胜感激,并且可能会在类似情况下帮助其他人。
期望的行为
将use()
实例应用于所有路由,但由以下人员处理的路由除外:
app.use(express.static("dist"));
实际行为
use()
正在应用于所有路线,包括由以下人员处理的路线:
app.use(express.static("dist"));
设想
为了保护对 API 的访问,我使用了 Lynda.com 教程中描述的模型:
在伪代码中,模型本质上包括:
use()
检查是否已发送 jwt 令牌 的全局实例- 如果已发送令牌,则验证令牌
- 如果验证失败或未发送令牌, 它将
req.user
属性设置为undefined
- 否则,
req.user
如果验证成功,它将属性设置为解码的 jwt 值 - 后续中间件根据
req.user
该模型适用于所有意图和目的。
但是,我最近添加了一些控制台日志记录,并且可以看到正在对两者执行验证:
- api 请求(期望的行为)
app.use(express.static("dist"))
通过此约定提供的静态文件(不良行为)
问题
如何将验证use()
实例应用于所有路由,由app.use(express.static("dist"))
.
我试过的
我想我已经通过移动2
上面部分的代码部分解决了这个问题1
。
// 01. verification use() called on all requests
app.use((req, res, next) => {
// if jwt authorisation has been sent in headers, verify it
if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
console.log("jwt verification sent, verifying...");
try {
// this is synchronous as it has no callback
req.user = jsonwebtoken.verify(req.headers.authorization.split(' ')[1], 'RESTFULAPIs');
console.log("jwt verified, will return decoded value");
} catch (err) {
req.user = undefined;
console.log("jwt verification failed, user will remain undefined: " + err);
}
// move to the next piece of middleware
next();
}
// if jwt authorisation has not been sent in headers
else {
console.log("jwt verification not sent, leaving user as undefined");
console.log(req.originalUrl);
req.user = undefined;
// move to the next piece of middleware
next();
}
});
// 02. use() for serving static files
app.use(express.static("dist"));
// 03. middleware to check if login has been verified
const api_login_required = (req, res, next) => {
// if token verification was successful and the user property exists
if (req.user) {
// move to the next piece of middleware
next();
}
// otherwise, return unauthorised user message
else {
res.json({ verification: 0 });
}
}
// 04. middleware called in route handlers
app.route("/api/:api_version/users/private_data")
.get(api_login_required, api_users_private_data_get)
.post(api_login_required, api_users_private_data_post);
解决方案
中间件总是控制他们编写顺序的从到按钮的流程。喜欢
if (example 1)code like
app.use((req,res, next)=>{// middleware 1; next()} )
app.get('/rot1', (req, res)=> res.status(200).send('route 1'));
app.get('/rot2', (req, res)=> res.status(200).send('route 2'));
In this case, middleware appears in both route1, route because of middleware set at the top of the route.
If (example 2)code like
app.use((req,res, next)=>{// middleware 1; next()} )
app.get('/rot1', (req, res)=> res.status(200).send('route 1'));
app.use((req,res, next)=>{// middleware 2; next()} )
app.get('/rot2', (req, res)=> res.status(200).send('route 2'));
Here middleware1 applied in both route1 and route 2
But middleware2 applied only on route2.
But you can also define specific middleware for each route
function middleware1(req, res, next){
next();
}
function middleware2(req, res, next){
next();
}
app.get('/rot1', middleware1, (req, res)=> res.status(200).send('route 1'));
app.get('/rot2', middleware2, (req, res)=> res.status(200).send('route 2'));
Here middleware1 only applied on route1 and middleware2 only applied on route2.
也许上面的解释对你有帮助!!
推荐阅读
- java - Firebase - 无法读取应用程序界面上的数据 - Android Studio
- ios - Master-Detail-Application更改“返回”按钮iPad(Objective-C)
- c++ - 使用在作用域内生成的指针初始化静态成员
- windows - 如何告诉 CMake 输出包搜索路径?
- python - 如何从 tf 估计器中获取张量(不是变量)?
- user-interface - Google Apps 脚本中的自定义交互式 UI 框
- typescript - 打字稿中可选参数和默认参数的类型
- flutter - Flutter - 3rd 方 JAR 代码将在 Android Studio 中运行,而不是在 VS Code 中运行
- python - ndexError: 只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引
- algorithm - 正在寻找从场地中心寻找完美“蛇”的算法?