javascript - 使用默认路由的 Express.js 路由

标签 javascript node.js express

我有以下 Express.js 代码:

router = express.Router()
fs.readdirSync('./controllers').forEach(function (file) {
  if(file.substr(-3) == '.js') {
      route = require('./controllers/' + file);
      route.controller(router);
  }
});
app.use('/', router);

效果不错。我没有在我的 Controller 中设置 '/' 路由的路径,我的 Express.js 服务器默认从 'public' 文件夹呈现 'index.html' - 这就是我想要的。现在我想添加 '*' 路由,所以 Express.js 从 'public' 文件夹返回 'index.html' - 它是静态文件,不需要渲染,只是返回。我该怎么做?谢谢

最佳答案

如果您希望您的服务从您的根路径提供 public/index.html,您可以像这样简单地使用 express.static:

app.use(express.static('public'));

express.static 默认会将 index.html 视为您的索引文件,您可以在第二个参数中进行配置:

app.use(express.static('public', {index: 'myIndex.html'}))

另请注意,您不必按原样指定 app.use 的根目录。只需这样做:

app.use(router);

我什至建议您的 route.controller() 方法不是必需的。如果您的每个 Controller 都导出了它们自己的 express.Router(),您只需在迭代器中执行 app.use(myController)

关于javascript - 使用默认路由的 Express.js 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30556159/

相关文章:

javascript - ESLint eslint-plugin-react 箭头函数

javascript - AjaxFileUpload cancelUpload() 不起作用

angularjs - 自动对焦在某些条件后将启用的禁用字段

javascript - 在 javascript 中返回另一个函数是一个好方法吗?

javascript - `.replaceChild()` 上 `this` 抛出 NotFoundError : DOM Exception 8

javascript - 使用 hubot-test-helper 和 jest 测试 Hubot

node.js - 为什么链接 fuser 命令和 Node 应用程序不按顺序工作?

node.js - EBUSY : resource busy or locked in Docker when trying to do npm install

node.js - nodejs-express - 在主数据库上实现 Redis 缓存作为 mongodb

node.js - 具有快速网关的微服务 : routes return 404 error