node.js - 如何在路由器级别使用快速中间件
问题描述
我正在尝试为路由器级别的每个请求添加一个简单的中间件功能。
文档说明:
对路由器的每个请求都会执行一个没有挂载路径的中间件函数
在我的应用程序中,我只有一个带有一个端点的路由器,该端点正在侦听每个请求,并且我将中间件功能放置在此端点之上,但中间件永远不会启动。
快速设置:
const initializeExpress = (): void => {
const port = process.env.PORT;
const app = express();
app.use(helmet());
app.use(express.json());
app.use(cors());
app.use('/api', Router);
app.listen(port, () => {
console.log(`Listening for requests at http://localhost:${port}`);
});
};
我的路由器代码:
const Router = express.Router();
Router.use((req, res, next) => {
const token = req.header('authorization');
if (!token) res.status(401).send({ message: 'Unauthorized' });
const isAuthenticated = isAuthorized(token!);
if (isAuthenticated) {
next();
} else {
res.status(401).send({ message: 'Unauthorized' });
}
});
Router.get(
'/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?',
async (req, res): Promise<void> => {
const routeParams = filterRouteParams(req.params);
const path = basePath + getPathFromRouteParams(routeParams) + '/data.json';
if (await pathExists(path)) {
const data = await getJsonFromPath(path);
if (!isEmpty(data)) {
res.status(200).json(data);
return;
}
res.status(400).send({ message: 'Data not found' });
}
}
);
我在这里做错了什么?
解决方案
中间件将在哪个路由上处于活动状态,您需要对其进行定义。
有两种方法可以做到这一点
首先,在您的路由之前调用中间件:
const Router = express.Router();
const myMiddleware = (req, res, next) => {
const token = req.header('authorization');
if (!token) res.status(401).send({ message: 'Unauthorized' });
const isAuthenticated = isAuthorized(token!);
if (isAuthenticated) {
next();
} else {
res.status(401).send({ message: 'Unauthorized' });
}
}
Router.get(
'/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?',
myMiddleware(), //Call middleware here
async (req, res): Promise<void> => {
const routeParams = filterRouteParams(req.params);
const path = basePath + getPathFromRouteParams(routeParams) + '/data.json';
if (await pathExists(path)) {
const data = await getJsonFromPath(path);
if (!isEmpty(data)) {
res.status(200).json(data);
return;
}
res.status(400).send({ message: 'Data not found' });
}
}
);
其次,为您定义的所有路由调用中间件:
const Router = express.Router();
const myMiddleware = (req, res, next) => {
const token = req.header('authorization');
if (!token) res.status(401).send({ message: 'Unauthorized' });
const isAuthenticated = isAuthorized(token!);
if (isAuthenticated) {
next();
} else {
res.status(401).send({ message: 'Unauthorized' });
}
}
Router.use('/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?', myMiddleware());
Router.get(
'/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?'
async (req, res): Promise<void> => {
const routeParams = filterRouteParams(req.params);
const path = basePath + getPathFromRouteParams(routeParams) + '/data.json';
if (await pathExists(path)) {
const data = await getJsonFromPath(path);
if (!isEmpty(data)) {
res.status(200).json(data);
return;
}
res.status(400).send({ message: 'Data not found' });
}
}
);
推荐阅读
- windows - 列表框项目表示为图标?
- python - 在 Pandas 中加快处理速度
- ruby-on-rails - 编辑页面没有保存更改 - Cocoon Gem
- python - 如何使用python从spark数据帧中读取十进制精度值
- web-crawler - 服务器如何知道请求不是来自浏览器
- sas - SAS中total = sum(of q1-q4)和total = sum(q1-q4)之间的差异
- amazon-dynamodb - 需要一些关于大数据 ETL 作业成本效益设计的建议
- arduino-c++ - 无法为 Encoder.h 构建包装类,在调用包装类构造函数之前调用了编码器构造函数
- javascript - 如何在 vuejs 的 storybook 故事中导入 scss 文件和图像?
- android - OnTouchEventListener返回值的含义