首页 > 解决方案 > Router.get 用于在 koa 中渲染 index.HTML

问题描述

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

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

我是 Koa 的新手。请帮忙

标签: htmltypescriptfrontendrouterkoa2

解决方案


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

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

  • 索引.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

推荐阅读