Skip to content Skip to sidebar Skip to footer

Koa.js - Serving Static Files And Rest Api

I'm new to koa.js library and I need some help. I'm trying to make simple REST application using koa. I have a static html and javascript files I want to serve on route / and REST

Solution 1:

It was a little hard for me to follow what you were doing in your example code... Here is a simple example that does everything your wanting:

'use strict';
let koa     = require('koa'),
    send    = require('koa-send'),
    router  = require('koa-router')(),
    serve   = require('koa-static');

let app = koa();
// serve files in public folder (css, js etc)
app.use(serve(__dirname + '/public'));

// rest endpoints
router.get('/api/whatever', function *(){
  this.body = 'hi from get';
});
router.post('/api/whatever', function *(){
  this.body = 'hi from post'
});

app.use(router.routes());

// this last middleware catches any request that isn't handled by// koa-static or koa-router, ie your index.html in your example
app.use(function* index() {
  yieldsend(this, __dirname + '/index.html');
});

app.listen(4000);

Solution 2:

const root = require('path').join(__dirname, 'client', 'build');
app.use(serve(root));

app.use(async ctx => {
    awaitsend(ctx, `/index.html`, {
        root
    });
});

Solution 3:

From @Nurpax in the comments:

app.use(asyncfunction (ctx, next) {
  returnsend(ctx, '/index.html', { root: paths.client()
})
.then(() =>next()) }) 

The key thing was to specify {root:<some path>}. I think the problem in my case was that for security reasons, send doesn't allow relative paths or paths outside of the project tree. Specifying the root param and then giving a filename relative to that seemed to fix the problem. I guess I expected koa-send to log an error/warning on the node output about this.

Solution 4:

This piece of code is working fine for me.

I'm serving auto files images and videos in koa.

const koa = require('koa');
const koaRouter = require('koa-router');
const cors = require('@koa/cors');
const koaBody = require('koa-bodyparser');
const koaSend = require('koa-send'); 
const serve = require('koa-static');
const app = newkoa();
const router = newkoaRouter();

router.get('/public/audios/:item', async ctx => {
    const { item } = ctx.params;
    awaitkoaSend(ctx, { root: `./public/audios/${item}` });
});

router.get('/public/videos/:item', async ctx => {
    const { item } = ctx.params;
    awaitkoaSend(ctx, { root: `./public/videos/${item}` });
})

router.get('/public/images/:item', async ctx => {
    const { item } = ctx.params;
    awaitkoaSend(ctx, { root: `./public/images/${item}` });
})

app
  .use(serve('./public'))
  .use(koaBody({ jsonLimit: '100mb', formLimit: '100mb', textLimit: '100mb' }))
  .use(cors())
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(3000);

Post a Comment for "Koa.js - Serving Static Files And Rest Api"