Express 4:重定向后我无法获取我的静态文件。

4

我遇到了Express 4和静态文件的问题。在成功登录后,我将我的Web应用程序重定向到“/home/userId”,但是接下来,我会在所有静态文件上收到404错误。这是我的路由器:

router.get('/home/:userid', function(req, res, next) {
  // TODO check if token is valid
 User.findById(req.params.userid).exec(function(err, find) {
    if (err) return next(err);
    if (!find) {
      return res.json(utils.createErrorJsonResponse(404, "User not found!"));
    }
    return res.render('home', {
      title: 'Organizator',
      user: find
    });
  })
});

我认为展示我的jade文件并没有什么用,唯一重要的是有很多导入的脚本,但是举个例子,这是我如何加载CSS文件:

  link(href='css/style.css', rel='stylesheet')

这是我设置静态文件的方法。
  app.use(express.static(config.root + '/public',{ maxAge: 86400000 }));

其中'config.root'是我的根目录:

path.normalize(__dirname + '/..')

如我之前所说,如果我连接到基本页面,那么在我的情况下:

http://localhost:3000

所有我的静态文件都已经被导入,但当我重定向后就会出现404错误。那么我该怎么解决呢?例如,我有一个名为 'style.css' 的样式文件。在基本页面('http://localhost:3000)中,从控制台可以看到:
Request URL:http://localhost:3000/css/style.css
Request Method:GET
Status Code:200 OK (from cache)

从 'http://localhost:3000/home/' 开始:

Request URL:http://localhost:3000/home/css/style.css
Request Method:GET
Status Code:404 Not Found

所以问题是'/home', 但是我如何从静态文件请求中“移除”它呢?谢谢。

1
你是如何在JADE中加载文件的?我认为这对于你提供的错误很重要。你是使用link(href="/css/style.css")吗? - Jose Hermosilla Rodrigo
嗨。我已经编辑过了,就像我说的那样,没有玉错误,否则我的基本页面就无法工作。 - Francesco Z
3
确保你的href或src链接以“/”开头,这样看起来像“/css/style.css”或“/js/some-file.js”。没有初始“/”,它就是相对路径,浏览器会将其转换为“/home/userId/css/style.css”,这不是你想要的。 - Molda
1
正如我在评论中建议您的那样,您的文件正在JADE中加载文件。@Molda已经更详细地解释了您的错误。 - Jose Hermosilla Rodrigo
1个回答

5

正如@Molda在评论中所解释的那样,请确保您的链接以/开头,否则路径将相对于实际路由http://localhost:3000/home而言。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接