javascript Koa.js - 提供静态文件和 REST API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32721311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:39:53  来源:igfitidea点击:

Koa.js - serving static files and REST API

javascriptnode.jsreststatickoa

提问by suricactus

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/.

我是 koa.js 库的新手,我需要一些帮助。我正在尝试使用 koa 制作简单的 REST 应用程序。我有一个静态 html 和 javascript 文件,我想在//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-serverlibraries and neither works so I'm doing something wrong.

我试过koa-static, koa-static-folder,koa-static-server库,但都不起作用,所以我做错了。

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

我试过这个并且它有效,但我无权访问我的 REST api:

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

回答by James Moore

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);

回答by hoodsy

From @Nurpax in the comments:

来自@Nurpax 的评论:

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.

关键是要指定{root:<some path>}. 我认为我的问题是出于安全原因,发送不允许相对路径或项目树之外的路径。指定根参数,然后给出相对于该参数的文件名似乎可以解决问题。我想我希望 koa-send 在节点输出上记录一个关于这个的错误/警告。

回答by Fausta Leonardo

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

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