【问题标题】:Why is Koa's redirect throwing 404 after another redirect?为什么 Koa 的重定向在另一个重定向之后抛出 404?
【发布时间】:2021-04-05 23:58:16
【问题描述】:

我有以下代码...

const auth = new Authentication();
mainApp.use(auth.checkToken.bind(auth));
mainApp.use(mount('/auth', auth.app));

class Authentication{
    constructor() {
        this.redirectApp = new Koa();
        this.redirectApp.use(this.onLogin);
        this.logoutApp = new Koa();
        this.logoutApp.use(this.onLogout);
        this.callbackApp = new Koa();
        this.callbackApp.use(this.onCallback);
        this.app = new Koa();
        this.app.use(mount('/login', this.redirectApp));
        this.app.use(mount('/callback', this.callbackApp));
        this.app.use(mount('/logout', this.logoutApp));
    }
    checkToken(ctx, next){
        if(ctx.path  === "/auth/login" || ctx.path  === "/auth/callback" || ctx.path === "/auth/logout"){
            next();
        } else{
            const cookie = ctx.cookies.get("userInfo");
            if(cookie == null){
                ctx.redirect("/auth/login");
            } else{
                const userInfo = JSON.parse(ctx.cookies.get("userInfo"));
                if(userInfo.accessToken){
                    // TODO: check the token;
                    next();
                } else{
                    ctx.redirect("/auth/login");
                }
            }
        }
    }
    onLogin(ctx){
        const path = `https://${domain}/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUrl}&scope=email&audience=${audience}&state=`;
        ctx.redirect(path);
    }
}

当我转到根目录 (http://localhost:3000) 时,我可以看到它点击了 ctx.redirect(path);,但我得到了 404。如果我注释掉 mainApp.use(auth.checkToken.bind(auth)); 并直接点击 /auth/login,它工作正常。

为什么我不能在初始中间件之后进行重定向?

【问题讨论】:

    标签: javascript koa koa2


    【解决方案1】:

    通过等待下一个来修复它...

    async checkToken(ctx, next){
        if(ctx.path  === "/auth/login" || ctx.path  === "/auth/callback" || ctx.path === "/auth/logout"){
            await next();
        } else{
            const cookie = ctx.cookies.get("userInfo");
            if(cookie == null){
                ctx.redirect("/auth/login");
            } else{
                const userInfo = JSON.parse(ctx.cookies.get("userInfo"));
                if(userInfo.accessToken){
                    // TODO: check the token;
                    await next();
                } else{
                    ctx.redirect("/auth/login");
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 2020-03-14
      • 2021-01-23
      • 2018-11-13
      • 1970-01-01
      相关资源
      最近更新 更多