Koa.js - serving static files and REST API

I am new to koa.js library and I need help. I am trying to make a simple REST application using koa. I have static html and javascript files that I want to serve on the route / and REST API, which can be accessed 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 tried the koa-static , koa-static-folder , koa-static-server libraries and didn't work, so I'm doing something wrong.

I tried this and it works, but I do not have access to my REST api:

 var app = require('koa')(); app.use(require('koa-static')('../ui/app/', {})); 
+5
source share
2 answers

It was a little difficult for me to keep track of what you did in your code example ... Here is a simple example that does everything you need:

 '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); 
+10
source

From @Nurpax in the comments:

 app.use(async function (ctx, next) { return send(ctx, '/index.html', { root: paths.client() }) .then(() => next()) }) 

The main thing was to specify {root:<some path>} . I think the problem in my case was that, for security reasons, send does not allow relative paths or paths outside of the project tree. Specifying the root parameter and then providing the file name with respect to this seemed to fix the problem. I assume that I was expecting koa-send to trigger an error / node exit warning about this.

+1
source

Source: https://habr.com/ru/post/1232038/


All Articles