本文介绍了Koa.js - 提供静态文件和REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是koa.js图书馆的新手,我需要一些帮助。我正在尝试使用koa制作简单的REST应用程序。
我有一个静态的html和javascript文件,我想在路由 / 上提供服务,REST API从 / 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/.

这是我的项目目录树:

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 库并且都不起作用所以我正在做某事错误。

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

我试过这个并且它可以工作,但我无法访问我的REST api:

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/', {}));


推荐答案

我跟你说的有点困难在你的示例代码中...
这是一个简单的例子,可以完成你想要的一切:

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

这篇关于Koa.js - 提供静态文件和REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:32