无法从另一个模块中设置express.static

这工作

var express = require('express'); var app = express(); var request = require('request'); // initialize session, redis server will be used if it's running otherwise will store in memory require('./config/session.js')(app, function () { // configurations require('./config/bodyparser.js')(app); require('./config/cookieparser.js')(app); require('./config/compression.js')(app); //require('./config/other.js')(app, express); app.use(express.static('./public', { /*maxAge: 86400000*/})); app.listen(3000, function () { console.log('running...'); }); }); 

但如果我取消注释需要other.js和评论app.use它不。 这是other.js文件。

 module.exports = function (app, express) { app.use(express.static('../public', { /*maxAge: 86400000*/})); return app; } 

尝试了不同的亲属path,但都失败了。 这是项目结构

 -config --other.js -public -app.js 

我得到的错误是

Cannot GET /index.html

在我的浏览器,在控制台没有错误。

这里的问题是,当你require other.js文件时,相对path是使用app.js的cwd。 避免这种情况(避免相对path的麻烦)的最好方法是使用path.resolve__dirnamevariables。

__dirname是一个特殊的Node.jsvariables,它总是等于它所在的文件的当前工作目录。所以,与path.resolve结合,你总是可以确定,无论文件被require在哪里,它都使用正确的path。

在other.js中:

 var path = require('path'); .... app.use(express.static(path.resolve(__dirname, '../public'))); 

或者你可以简单地更新other.js使用./public但我相信上面是更好的做法,如果你移动app.jsrequire other.js在不同的文件夹,它不会正确parsing

有关path.resolve信息在这里