首页 > 解决方案 > 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');
}

标签: node.jsreactjsexpressmiddleware

解决方案


您的代码有语法错误,可能值得先解决这个问题,看看它是否会导致您遇到的错误:

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.
}

推荐阅读