Express Static无法按预期工作

时间:2017-05-11 05:17:27

标签: node.js express

我的Node.js网站运行静态html,我的server.js文件位于:

const express = require('express');

const app = express();

app.use(serve('/client', {
    extensions: ['html']
}));

const server = app.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
  console.log('server is running at %s', server.address().port);
});

我希望当我的网址为:

http://www.example.com/my-file-name

这是指向这个静态文件:

http://www.example.com/my-file-name.html

但是,我收到以下回复:

Cannot GET /my-file-name

我是否误解了Express Static的工作原理?或者我的server.js文件配置错误了吗?

更新

•这是我的文件系统的屏幕截图: https://www.dropbox.com/s/fyd818obfbfmdin/Screenshot%202017-05-11%2016.02.46.png?dl=0

•我删除了快速静态模块,因为有人指出Express已将它捆绑在一起。

2 个答案:

答案 0 :(得分:0)

传递给serve()的路径是本地文件系统路径,该路径将用作服务文件的根目录。如果/client作为本地文件系统上的绝对路径不存在,则应使用正确的(可能是绝对的)路径(例如__dirname + '/client'如果client是同一目录中的子目录。脚本)。

答案 1 :(得分:0)

来自robertklep的这个修复使它对我有用:

var fs        = require('fs');
var publicdir = __dirname + '/public';

app.use(function(req, res, next) {
  if (req.path.indexOf('.') === -1) {
    var file = publicdir + req.path + '.html';
    fs.exists(file, function(exists) {
      if (exists)
        req.url += '.html';
      next();
    });
  }
  else
    next();
});
app.use(express.static(publicdir));

链接到我从中获取的帖子:Any way to serve static html files from express without the extension?