【问题标题】:Express : unable to load the intended path with middlewaresExpress:无法使用中间件加载预期路径
【发布时间】:2019-05-23 10:58:12
【问题描述】:

我是 Express 的初学者,我正在使用中间件实现一个相当奇怪的功能。在这里,我调用一个由其中间件获取的 URL,然后在 next() 上调用另一个中间件。现在在第二个中间件的next() 中,我需要加载组件,但问题是,在第一个中间件的next() 之后,URL 没有改变。

代码:

Express 应用程序:路由器:

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.js reactjs express middleware


    【解决方案1】:

    您的代码有语法错误,可能值得先修复它,看看它是否会导致您遇到的错误:

    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) {...} 不会返回一个完整的值,因此不会触发链中的下一个中间件。

    试试:

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

    【讨论】:

      猜你喜欢
      • 2015-06-25
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多