我是koa.js库的新手,需要一些帮助。我正在尝试使用koa制作简单的REST应用程序。我有一个静态的html和javascript文件,我想在路由/和REST中从/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:
var app = require('koa')();
app.use(require('koa-static')('../ui/app/', {}));发布于 2015-09-22 16:57:01
我很难理解你在你的示例代码中所做的.下面是一个简单的例子,它可以实现您想要的一切:
'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);发布于 2020-04-02 07:32:23
const root = require('path').join(__dirname, 'client', 'build');
app.use(serve(root));
app.use(async ctx => {
await send(ctx, `/index.html`, {
root
});
});发布于 2016-09-03 13:53:29
来自@Nurpax的评论:
app.use(async function (ctx, next) {
return send(ctx, '/index.html', { root: paths.client()
})
.then(() => next()) }) 关键是指定{root:<some path>}。我认为在我的例子中的问题是,出于安全考虑,send不允许项目树之外的相对路径或路径。指定根param,然后给出一个相对于它的文件名,似乎解决了问题。我想我期望koa在节点输出上记录一个错误/警告。
https://stackoverflow.com/questions/32721311
复制相似问题