【问题标题】:Express js getting 404 for all static files in a directoryExpress js 为目录中的所有静态文件获取 404
【发布时间】:2016-01-24 05:51:06
【问题描述】:

为了方便我的静态文件,我有多个目录。 我的一些静态文件在客户端目录中,一些仪表板相关文件在 src 目录中,所以现在我的目录结构如下

/
|
client //static files and other stuff
server //server side express, app, controller, models etc
src //other static files

我有两个 Angular 应用程序,一个在客户端文件夹中,另一个在 src 文件夹中,我的服务器端路由如下 -

app.route('/app/dashboard-v1').get(function(req,res){
        res.sendFile(path.join(__dirname, '../src', 'index.html'));
    });

    // All undefined asset or api routes should return a 404
    app.route('/:url(api|img|src|auth|components|app|bower_components|assets)/*')
        .get(errors[404]);

    // All other routes should redirect to the index.html
    app.route('/*')
        .get(function (req, res) {
            res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
        });

所以我的第一个 Angular 应用程序位于 app/dashboard-v1 中,所有其他 url 都被重定向到 app2

我正确获取了我的 app2 中的所有文件,但我的第二个应用程序中的所有其他文件都得到了 404。 现在如果我注释掉

//  app.route('/:url(api|img|src|auth|components|app|bower_components|assets)/*')
            .get(errors[404]);

我从第一个应用程序的所有文件中的第二个应用程序获取我的 index.html,而不是 404 错误

我的快递配置如下——

if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', path.join(config.root, 'public'));
    app.use(morgan('dev'));
  } else {
    app.use(require('connect-livereload')());
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.use(express.static(path.join(config.root, 'src')));
    app.set('appPath', path.join(config.root, 'client'));
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }

我假设我的路线有问题。我该如何解决 ? 在第一个应用程序(app/dashboard-v1)的 index.html 中,我添加了

<base href="/src/" />

并且我的 index.html 中的所有链接都是相对的,如下所示是 src/index.html (app/dashboard-v1 url app) 中的一个块-

<script src="vendor/angular/angular-animate/angular-animate.js"></script>
  <script src="vendor/angular/angular-cookies/angular-cookies.js"></script>

当我在浏览器中打开网络控制台时,向服务器发出的请求是这样的 -

Request URL:http://localhost:9000/src/vendor/angular/angular-animate/angular-animate.js

我在浏览器控制台中收到 404 状态码

【问题讨论】:

    标签: javascript angularjs express routes http-status-code-404


    【解决方案1】:

    您是否在示例的 / 目录上运行该应用程序?

    我认为您应该将 __dirname 设置为静态文件夹

    app.use('/',express.static(__dirname));
    

    或者如果你愿意,你可以像这样设置特定的文件夹:

    app.use("/public", express.static(__dirname + "/public"));
    app.use("/public2", express.static(__dirname + "/public2"));
    

    【讨论】:

    • 感谢您的回答,这就是我所缺少的。你也可以像这样避免字符串连接。
      app.use('/public', express.static(path.join(__dirname, 'public')));
    猜你喜欢
    • 2013-06-27
    • 2020-10-15
    • 2014-04-19
    • 2011-08-20
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多