node.js - Express:无法使用中间件加载预期路径
问题描述
我是 Express 的初学者,我用中间件实现了一个相当奇怪的功能。在这里,我调用了一个 URL,该 URL 由其中间件获取,然后在next()
另一个中间件上被调用。现在在next()
第二个中间件中我需要加载组件,但问题是,在第一个中间件的next()
.
代码 :
快递应用程序:路由器:
app.use('/common/global/login', mainHandler);
app.use('/common/*', subhandler, SuccessComponent);
中间件:
export function mainHandler(req, res, next) {
const global-url= "someURL"
if (global-url) {
return fetch(global-url)
.then((response) => response.json())
.then((response) => {
if (response.data) {
next();
} else {
throw Error(response.statusText);
}
})
.catch((error) => {
res.redirect('/session-expired');
next(error);
});
}
res.redirect('/session-expired');
}
export function subhandler (req, res, next) {
const other_url= "someOtherURL"
return fetch(other_url)
.then((response) => response.json())
.then((response) => {
if (response.data) {
// here it not loading the SUCCESSCOMPONENT as the URL still remains /common/global/login
return next();
}
throw Error(response.statusText);
})
.catch((error) => {
next(error);
res.redirect('/session-expired');
});
}
res.redirect('/session-expired');
}
解决方案
您的代码有语法错误,可能值得先解决这个问题,看看它是否会导致您遇到的错误:
export function mainHandler(req, res, next) {
const global-url= "someURL"
if (global-url) {
return fetch(global-url)
...
您不能定义包含连字符的变量-
,因为这读作减法运算符。
const global-url = ...
, 应该const global_url = ...
当然,更新您调用此变量的所有实例。
在您的代码的当前状态下,next()
没有被第一个中间件调用,因为if (global-url) {...}
不会返回一个 thruthy 值,因此不会触发链中的下一个中间件。
尝试:
export function mainHandler(req, res, next) {
const global_url= "someURL"
if (global_url) {
return fetch(global_url)
.then((response) => response.json())
.then((response) => {
if (response.data) {
next();
} else {
throw Error(response.statusText);
}
})
.catch((error) => {
res.redirect('/session-expired');
next(error);
});
}
res.redirect('/session-expired');
// Note that if this 'if' is not satisfied, 'next()' is not called.
}
推荐阅读
- typescript - 如何在打字稿中获取泛型类型的参数
- macos - 如何使用脚本安装 mac os 应用程序?
- arrays - C中文件范围错误的可变修改“数据”
- swiftui - 为什么这个 SwiftUI LazyHStack 不断更新?
- c - 如何在 C 中使用指针时实现 Scanf
- python - Django ManyToManyField 反向关系问题
- javascript - Firestore 在 React Native 中显示查询结果
- html - CSS/HTML CSS 样式表锁定更改并且无法恢复它们?
- android - 如何为 Android TabLayout 添加水平滚动指示器
- mongodb - 需要得到结合数据库及其集合的查询结果