Node.js - 由需要静态导出的路由引起的错误

时间:2016-01-05 18:32:04

标签: node.js

我的Nodejs服务器的目录结构是这样的(它已被简化):

|-server.js
|-public
  |-static
    |-content
      |-footer.json
      |-header-footer.js
      |-header.json
|-routes
  |-home.js
  |-index.js

相关的/server.js代码:

var routes = require('./routes/index.js');
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// GET home page
app.get('/', routes.home);

相关的/routes/index.js代码:

// GET home page
exports.home = require('./home.js');

最后,相关的/routes/home.js代码:

var content = require('../static/content/header-footer.js');

服务器在最后一行(/routes/home.js中的第一行代码)崩溃。我还尝试了require(/static/content/header-footer.js)require(../content/header-footer.js)require(/content/header-footer.js);没有一个有用。

我在nodejs.log中收到的错误消息是:

Error: Cannot find module '../static/content/header-footer.js'
    at Function.Module._resolveFilename (module.js:337:15)
    at Function.Module._load (module.js:287:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/var/app/current/routes/home.js:1:77)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
module.js:339
    throw err;
    ^

路由是否可以要求静态javascript导出?如果是这样,我做错了什么?如果没有,我可以做些什么?

此外,以下是我的/public/static/content/header-footer.js文件:

// GET modules
var fs = require('fs');
// Header content
exports.header = fs.readFileSync('./header.json', 'utf8');
exports.header = JSON.parse(exports.header);
// Footer content
exports.footer = fs.readFileSync('./footer.json', 'utf8');
exports.footer = JSON.parse(exports.footer);

我想要注意的是,服务器在我刚刚推出的这个重大更新之前运行得很好。因此,虽然我是Nodejs的新手,但我已经让它正常运行了。如果我能让这个技巧发挥作用,它将增加我的代码的可重用性,减少代码大小,并提高可维护性。

感谢。

修改

所以似乎在/routes/home.js中将var content = require('../static/content/header-footer.js');更改为var content = require('../public/static/content/header-footer.js');就可以了。但我很好奇为什么后者有效而前者没有。

更详细的目录结构是

|-server.js
|-public
  |-static
    |-bootstrap
      |-css
        |-theme
          |-flatly
            |-bootstrap.css
    |-content
      |-footer.json
      |-header-footer.js
      |-header.json
|-routes
  |-home.js
  |-index.js
|-views
  |-layout.jade

/views/layout.jade包含以下行:

link(href="../static/bootstrap/css/theme/flatly/bootstrap.css", rel="stylesheet")

更新了问题:

如何要求路由中的方法需要指定完整路径(即../public/static/),而jade / html中的引用则不需要(即../static/)?

这是我困惑的根源。我认为在服务器后端访问它与在前端访问它之间的区别。

1 个答案:

答案 0 :(得分:0)

因为路径,你应该在其上添加公开

var content = require('../public/static/content/header-footer.js');