node.js - 无法从另一个模块设置express.static

标签 node.js express

这有效

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/

相关文章:

node.js - Socket.io NodeJS 聊天 : Why do messages emit multiple times?

node.js - 是否可以在 node.js 请求中设置无限超时?

javascript - 在执行之前将命令行参数注入(inject) JSON

express - ExpressJS 中的 CSRF 保护

javascript - 我们可以用 Mongoose 检索 Node js中两个表的数据吗

javascript - 将数组与错误合并为单一类型

javascript - Apollo 中的 GraphQL 架构存在问题

node.js - 如何从中间件获取api结果到路由

javascript - Express:下载返回空文件

node.js - 从 Golang 后端流式传输文件到 Node 前端