javascript - 为什么 Koa 的重定向在另一个重定向之后抛出 404?
问题描述
我有以下代码...
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
直接点击它可以正常工作。
为什么我不能在初始中间件之后进行重定向?
解决方案
用等待下一个修复它...
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");
}
}
}
}
推荐阅读
- javascript - iFrame window.postMessage - 数据始终为空字符串
- javascript - 使用动画(Javascript)动态更新 amCharts 4 世界地图?
- r - Fisher 对 2x10 偶然性的检验(单元格的 >20% 中的预期值 <6) - 解决 R 工作区错误,或者建议替代统计检验?
- cocoa - Quartz 2D 实现 html5 画布 globalCompositeOperation
- angular - TypeError:this.responsearray.find 不是函数角度
- installation - 我应该怎么办?我已经在桌面上安装了 NetBeans
- c - 即使我正在使用 select(),read() / recv() 函数会卡住吗?
- arrays - 用于 vlookup 的 Vba 代码将多个结果返回到单独的行中
- wordpress - 在 WordPress Gutenberg Block Development 中使用错误的片段标签
- python-3.x - 如何剥离拖尾空间?