Search code examples
htmltypescriptfrontendrouterkoa2

Router.get usage for rendering index.HTML in koa


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


Solution

  • 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

    • index.html
    • redirect.html (to demonstrate also redirecting)

    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

    • if you now in your browser call localhost:3000/index.html ... you get the content of index.html
    • if you call localhost:3000/ ... you get the content of redirect.html
    • you actually do not need the redirection middleware (shown above). koa-static redirects / calls to index.html