javascript - 设置静态 Assets 路径,使用 koa 和各种中间件路由端点

标签 javascript node.js koa

问题:

  1. 如何设置静态文件,以便这两个目录对我的 index.html 可见。
  2. 当您使用 koa-router 访问默认路由时,我如何发送我的 index.html ,而不是在我发出 AJAX Get 请求时仅发送 .json 文件?

要求:

我需要在我的应用中显示静态目录src/index.html

  • node_modules 需要为 js 库打开。
  • src/assets 需要打开图像。

我需要路由器有两个用途:

  • 1) 提供初始 index.html

  • 2) 我的数据库的 CRUD 端点。

注释:我完全愿意添加/删除任何中间件。但我不想改变我组织目录的方式。

目录结构:

directory structure

中间件:

app.js

var serve = require('koa-static');
var send = require('koa-send');
var router = require('koa-router')();
var koa = require('koa');
var app = koa();


// need this for client side packages.
app.use(serve('./node_modules/'));

// need this for client side images, video, audio etc.
app.use(serve('./src/assets/'));

// Will serve up the inital html until html5 routing takes over.
router.get('/', function *(next) {
    // send up src/index.html
});

// will serve json open a socket
router.get('/people', function *(next) {
  // send the people.json file
});

app.use(router.routes()).use(router.allowedMethods());

// errors
app.on('error', function(err, ctx){
  log.error('server error', err, ctx);
});

app.listen(3000);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Morningharwood</title>
</head>
<body>
  <h1>suchwow</h1>
  <img src="./assets/image1.png" alt="butts"> <!-- will 404 with routing -->

  <script src="./node_modules/gun/gun.js"></script> <!-- will always 404 -->
  <script>
    var gun = Gun(options);
    console.log(gun);
  </script>
</body>
</html>

最佳答案

嗯。碰巧我正在开发类似的应用程序

使用 koa-static 为您提供静态内容并为您的 api 端点使用 koa-router 没有问题。我从来没有直接使用过 koa-send 。但我认为你也不需要,考虑到你的设置

唯一重要的是将中间件附加到 koa 应用程序时的顺序。尝试首先为您的 Assets (甚至可能是index.html)附加 koa-static,然后为您的 api 使用 koa-router。尝试获取静态文件的请求永远不会到达路由器。这样路由器的唯一职责就是为你的 api 提供服务

如果这是不可能的(例如,因为您有一堆非静态 html 文件要服务器,请考虑每个应用程序可以有多个路由器,甚至可以将一个路由器嵌套在另一个路由器中

(如果答案不够,请花一些时间编写一个简单的示例。我会尽快发布)

编辑:添加了一个快速而肮脏的示例 here 。可能它不能开箱即用,但足以理解这个想法

关于javascript - 设置静态 Assets 路径,使用 koa 和各种中间件路由端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39927210/

相关文章:

node.js - 如何在Koa中为静态文件设置base?

node.js - 从 iojs 升级到 nodejs v4.4.4 后,自签名 SSL 不起作用

javascript - 动态下拉菜单创建问题(使用 AngularJS、CSS、JSON)

javascript - 我可以使用变量作为标识符来设置私有(private)类字段吗?如何?

javascript - 用 html javascript 替换奇数和偶数出现

node.js - 在大型 Mongo 集合中,如何使用 mongoose 仅​​检索 ID(或任何其他特定属性)?

node.js - async.each 嵌套在 async.waterfall 中

stream - 如何设置要在 Koa 响应中下载的文件的名称?

javascript - 如何使用 "in"和/或 "hasOwnProperty"缩小对象类型

javascript - 对多个 Field 和 div 使用动态 jQuery 函数