suricactus
suricactus

Reputation: 1238

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 API accessing from /api/.

This is my project directory tree:

project
├── server
│   ├── node_modules
│   ├── package.json
│   └── src
│       ├── config
│       ├── resources
│       └── server.js
├── ui
│   ├── app
│   ├── bower.json
│   ├── bower_components
│   ├── dist
│   ├── node_modules
│   ├── package.json
│   └── test

This is my source:

var app = require('koa')();
app.use(mount('/api/places', require('../resources/places')));

// does not work
var staticKoa = require('koa')();
staticKoa.use(function *(next){
  yield next;
  app.use(require('koa-static')('../ui/app', {}));
});
app.use(mount('/', staticKoa));

// does not work
app.use(mount('/', function*() {
    app.use(require('koa-static')('../ui/app/', {}));
}));

// does not work
app.use(mount('/', function*() {
    app.use(require('koa-static')('.', {}));
}));
// GET package.json -> 404 not found

I've tried koa-static, koa-static-folder, koa-static-server libraries and neither works so I'm doing something wrong.

I've tried this and it works, but I don't have access to my REST api:

var app = require('koa')();
app.use(require('koa-static')('../ui/app/', {}));

Upvotes: 12

Views: 23463

Answers (5)

Movahhedi
Movahhedi

Reputation: 584

What I ended up doing:

import * as fs from "fs";

myrouter.get("/data/:name", async (ctx, next) => {
    ctx.body = fs.createReadStream(`./data/${ctx.params.name}`);
});

However be aware that entering path/../../../some/path can bypass the root path.

Upvotes: 0

M. Hamza Rajput
M. Hamza Rajput

Reputation: 10266

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 = new koa();
const router = new koaRouter();

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

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

router.get('/public/images/:item', async ctx => {
    const { item } = ctx.params;
    await koaSend(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);

Upvotes: 0

Fausta Leonardo
Fausta Leonardo

Reputation: 91

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

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

Upvotes: 5

hoodsy
hoodsy

Reputation: 914

From @Nurpax in the comments:

app.use(async function (ctx, next) {
  return send(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.

Upvotes: 3

James Moore
James Moore

Reputation: 1901

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() {
  yield send(this, __dirname + '/index.html');
});

app.listen(4000);

Upvotes: 24

Related Questions