Koa.js – 提供静态文件和REST API
我是koa.js库的新手,需要一些帮助。 我正在尝试使用koa来制作简单的REST应用程序。 我有一个静态的html和JavaScript文件,我想在route /
和REST API从/api/
访问。
这是我的项目目录树:
project ├── server │ ├── node_modules │ ├── package.json │ └── src │ ├── config │ ├── resources │ └── server.js ├── ui │ ├── app │ ├── bower.json │ ├── bower_components │ ├── dist │ ├── node_modules │ ├── package.json │ └── test
这是我的来源:
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
我试过koa-static
, koa-static-folder
, koa-static-server
库,都没有工作,所以我做错了什么。
我试过这个,它的工作原理,但我没有访问我的REST API:
var app = require('koa')(); app.use(require('koa-static')('../ui/app/', {}));
对于我来说,遵循你在示例代码中做的事情是有点困难的……下面是一个简单的例子,它可以完成你想要的任何事情:
'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);
来自@Nurpax的评论:
app.use(async function (ctx, next) { return send(ctx, '/index.html', { root: paths.client() }) .then(() => next()) })
关键是指定{root:<some path>}
。 我认为在我的情况下,问题是,出于安全原因,发送不允许项目树外的相对path或path。 指定根参数,然后给出一个相对的文件名似乎解决了这个问题。 我想我希望koa发送logging在节点输出关于这个错误/警告。