Express js为目录中的所有静态文件获取404

Har*_*dha 2 javascript routes http-status-code-404 express angularjs

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

/
|
client //static files and other stuff
server //server side express, app, controller, models etc
src //other static files
Run Code Online (Sandbox Code Playgroud)

我有两个角度应用程序,一个在客户端文件夹中,另一个在 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'));
        });
Run Code Online (Sandbox Code Playgroud)

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

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

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

我从第一个应用程序的所有文件中的第二个应用程序中获取我的 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
  }
Run Code Online (Sandbox Code Playgroud)

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

<base href="/src/" />
Run Code Online (Sandbox Code Playgroud)

并且我的 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>
Run Code Online (Sandbox Code Playgroud)

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

Request URL:http://localhost:9000/src/vendor/angular/angular-animate/angular-animate.js
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

我认为您必须将 __dirname 设置为静态文件夹

app.use('/',express.static(__dirname));
Run Code Online (Sandbox Code Playgroud)

或者,如果您愿意,您可以设置特定的文件夹:

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));
Run Code Online (Sandbox Code Playgroud)