【发布时间】: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
尝试router.get('/', async ctx => ctx.redirect('index.html')) 进行初始路由,但失败了。
还有其他方法可以从router.get()重定向到index.HTML / index.ejs吗?
我是 Koa 的新手。请帮忙
【问题讨论】:
标签: html typescript frontend router koa2
仅仅重定向是不够的。你需要告诉 koa 如何提供静态文件……koa-static 是一个很好的包。
假设您将两个文件放入子目录./public
那就做吧
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的内容
/ 调用到 index.html
【讨论】: