koa - 如何在 koa 2 中有条件地重定向一些 URL

标签 koa koa2

这就是我的想法,伪代码。

const myRedirect = (routePath) => {
    newUrl = routePath;
    if (matches condition)
        newUrl = do_some_modification(routePath);       
    return next(newUrl); 
}

const myFunc = (routePath, myRedirect) => (newUrl, middleware) => {
    return (ctx, newUrl, next) => {
        return middleware(ctx, newUrl, next);
    }
};

请如何修改它以使其工作?

最佳答案

const route = async function(ctx, next){
    if(shouldRedirect){
        ctx.redirect('/redirect-url'); // redirect to another page
        return;
    }

    ctx.someData = getSomeData(); // ctx.someData will be available in the next middleware
    await next(); // go to next middleware
}

关于koa - 如何在 koa 2 中有条件地重定向一些 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46166691/

相关文章:

node.js - 提供静态图像 Koa.js

javascript - 重命名后如何在node.js中提供静态文件?

node.js - 尝试解析请求正文时,POST 请求挂起(超时),在 Firebase Cloud Functions 上运行 Koa

node.js - 结合 Typescript Koa-Router 和 Passport

node.js - 使用jest和supertest测试koa2时require返回空对象

error-handling - Koa 出错时显示自定义页面

javascript - 如何创建 Koa2 中间件来修改响应主体并在链中最后运行?

javascript - Koa.js 和流媒体。你如何处理错误?

javascript - 当 promise 在 javascript 中产生时会发生什么?

node.js - 使用 mocha/supertest 测试随机值