【问题标题】:`express.static()` keeps routing my files from the route`express.static()` 不断从路由中路由我的文件
【发布时间】:2015-03-24 11:17:25
【问题描述】:

在处理快速项目时,我尝试使用express.Router 对象来处理我的应用程序路由。在我的主应用程序文件中,我为我的所有静态文件(css、javascript、html)添加了一个静态路由。

app.js

var express = require('express');
var io = require('socket.io')(app);
var bodyParser = require('body-parser');
var router = require('./include/router');

var app = express();
app.use('/', router);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

io.on('connection', function(socket) {

});

app.listen(3000);

router.js

var express = require('express');
var path = require('path');

var router = express.Router();

router.get('/', function(req, res) {
  res.sendFile('/html/index.html');
});

module.exports = router;

当我尝试访问 localhost:3000 时,我得到一个显示 Error: ENOENT, stat 'C:\html\index.html' 的 404

此外,当我尝试直接访问静态路由时(http://localhost:300/html/index.html 我相信),但这给了我Cannot GET /html/index.html

这是我的公用文件夹的树

民众 ├───css ├───hmtl | └────index.html ├───img └────js

我是不是路由错了?我该如何解决?

【问题讨论】:

  • app.use 将为所有匹配路径参数的请求按照提供的顺序调用中间件。我建议在路由之前进行配置和静态分析。这应该可以解决问题。
  • 我试过切换路由器和静态线路,但没有成功,有没有机会从express.Router对象创建静态路由?
  • 您可能有两个问题。 res.sendFile('/html/index.html'); 没有意义,因为那是绝对路径,你可能是指res.sendFile(__dirname + '../public/html/index.html');。至于http://localhost:300/html/index.html,您的文件树示例有hmtl,这实际上是您机器上的拼写错误,还是只是示例?
  • 您也可以尝试为 app.use('/public', express.static(__dirnam + '/public')) 之类的静态变量提供路径,如果是这样,可能会清除任何路由冲突
  • 我已经修复了hmtl 的错字,并尝试了其他路径,但现在没有找到Error: ENOENT, stat 'C:\Users\James\Desktop\template\include..\public\html\index.html' 我还添加了静态路径。这些都不起作用:(

标签: node.js express static-files


【解决方案1】:

你必须颠倒你的路由器的顺序

app.use('/', router);
app.use(express.static(__dirname + '/public'));

表示你的路由器会先被调用,如果没有中间件处理请求,那么express会调用静态文件,所以如果你把静态中间件放在前面,express会先处理静态文件。

也建议先放静态中间件。

对于你的问题,你应该试试这个:

app.use(express.static(__dirname + '/public/html'));
app.use(express.static(__dirname + '/public'));
app.use('/', router);

Express 将首先在 public/html 文件夹中尝试静态文件,然后在其余的(包括 public/html)上尝试静态文件,我更喜欢将 html 文件放在 public 文件夹的根目录或不同的文件夹(例如 public-html,静态html)

【讨论】:

  • 由于某种原因,当在路由器中使用带有mergeParams:true 选项的参数时,这似乎不起作用,路由器将尝试在当前路由下提供静态文件,如/myuri/js/main.js,如下所述:@987654321 @
  • @loretoparisi 这正是我的问题,我找不到任何解决方案。我的带有参数的路由不会像我的其他路由一样加载到 css 和 js 源中。它尝试加载到路由的非参数化部分的目录中。就像如果路由是'/newItem:id',它会寻找一个名为newItem 的文件夹。为什么要这样做??
  • 我想我已经以某种方式解决了它。我将在这里发布解决方案。
  • 这是将 express 与 react 结合使用的好方法。如果您在 app.use 使用 express 路由器之后 app.use 静态构建文件,那么 express 将首先咨询路由器,然后才使用静态文件。例如,您想使用 router.get 对用户进行身份验证,然后才提供静态反应构建内容。
猜你喜欢
  • 1970-01-01
  • 2020-06-28
  • 2012-07-13
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多