【问题标题】:Router.get usage for rendering index.HTML in koaRouter.get 用于在 koa 中渲染 index.HTML
【发布时间】:2019-09-27 21:49:24
【问题描述】:

尝试router.get('/', async ctx => ctx.redirect('index.html')) 进行初始路由,但失败了。

还有其他方法可以从router.get()重定向到index.HTML / index.ejs吗?

我是 Koa 的新手。请帮忙

【问题讨论】:

    标签: html typescript frontend router koa2


    【解决方案1】:

    仅仅重定向是不够的。你需要告诉 koa 如何提供静态文件……koa-static 是一个很好的包。

    假设您将两个文件放入子目录./public

    • index.html
    • redirect.html(也用于演示重定向)

    那就做吧

    npm install koa
    npm install koa-static
    

    你的代码基本上应该是这样的:

    'use strict';
    const koaStatic = require('koa-static');
    const Koa = require('koa');
    const app = new Koa();
    
    // possible redirect middleware
    const redirect = async function(ctx, next) {
        if (ctx.request.url === '/') {
            ctx.redirect('redirected.html')
        } else {
            await next()
        }
    }
    
    app.use(redirect); // this will add your redirect middleware
    app.use(koaStatic('./public')); // serving static files
    
    app.listen(3000);
    

    备注

    • 如果你现在在浏览器中调用localhost:3000/index.html ...你会得到index.html的内容
    • 如果你打电话给localhost:3000/ ...你会得到redirect.html的内容
    • 您实际上不需要重定向中间件(如上所示)。 koa-static 重定向 / 调用到 index.html

    【讨论】:

    • 我想在重定向到我的 index.html 之前打两个服务调用。所以只有在成功响应时,我才会导航到 index.html。您能否为此提供任何解决方案?
    • 不确定你的意思。你能更明确地描述它吗?服务调用什么?它们也是异步的吗? DB或Rest调用? ...实际上,这大大扩展了您的问题。所以你原来的标题不合适了。也许只需将此标记为已回答并打开一个新的。
    • 假设我必须在渲染 html 之前调用一个 api(Rest 调用)。好吧,我将为这个问题打开一个新的。谢谢塞巴斯蒂安
    猜你喜欢
    • 1970-01-01
    • 2018-04-30
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2023-03-08
    • 2020-11-15
    相关资源
    最近更新 更多