这有效
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...'); });
});
但是如果我取消注释 require other.js 并注释 app.use 它不会。这是 other.js 文件。
module.exports = function (app, express)
{
app.use(express.static('../public', { /*maxAge: 86400000*/}));
return app;
}
尝试了不同的相对路径,但都失败了。这是项目结构
-config
--other.js
-public
-app.js
我得到的错误是
无法获取/index.html
在我的浏览器上,控制台中没有错误。
最佳答案
这里的问题是,当您require
other.js 文件时,相对路径正在使用app.js
的cwd。避免这种情况(并避免相对路径带来的麻烦)的最佳方法是使用 path.resolve
和 __dirname
变量。
__dirname
是一个特殊的 Node.js 变量,它始终等于其所在文件的当前工作目录。因此,与 path.resolve
结合使用,您始终可以确保无论文件在哪里被require
,它都会使用正确的路径。
在 other.js 中:
var path = require('path');
....
app.use(express.static(path.resolve(__dirname, '../public')));
或者您可以简单地更新 other.js 以使用 ./public
但我相信上面的做法是更好的做法,就像您移动 app.js
或 require
other.js 在不同的文件夹中,它将无法正确解析
有关 path.resolve
的信息 here
关于node.js - 无法从另一个模块设置express.static,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858750/