Tried router.get('/', async ctx => ctx.redirect('index.html'))
for the initial routing, but failed.
Is there any other method to redirect to index.HTML / index.ejs from router.get()
?
I'm new to Koa. Please help
It is not enough to just redirect. You need to tell koa how to serve a static file ... koa-static
is a good package for that.
Lets assume you place two files into a subdirectory ./public
Then do
npm install koa
npm install koa-static
You code then should basically look like:
'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);
Remarks
localhost:3000/index.html
... you get the content of index.html
localhost:3000/
... you get the content of redirect.html
/
calls to index.html