You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Express在子路径部署Angular应用:解决资源加载失败问题

问题描述

我已经在根路径(www.demodomain.com)部署了一个Angular应用,现在想在子路径www.demodomain.com/secondappp部署另一个Angular应用。目前index.html能正常加载,但main.js、polyfills.js这些资源死活加载不出来,附上我的代码:

server.js

const express = require('express');
const https = require('http');

const app = express();
const port = 4000;
app.use(express.static(__dirname + '/dist/secondappp/'));

app.get('/*', (req,res) => {
  res.sendFile(__dirname +'/dist/secondappp/index.html')
});

const server = https.createServer(app);
server.listen(port, () => console.log('worked'));

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <base href="/secondapp/">
  <meta content="width=device-width, initial-scale=1" name="viewport">
  <link href="favicon.ico" rel="icon" type="image/x-icon">
</head>
<body>
  <p>TESTING ANGULAR IN NODE JS</p>
<app-root></app-root>
</body>
</html>

解决方法

  1. 修正base href的拼写错误
    你的子路径是/secondappp,但index.html里的<base href="/secondapp/">少了一个p,得改成:

    <base href="/secondappp/">
    

    这个base标签是Angular加载资源的基准路径,路径不匹配直接导致资源请求失败。

  2. 给Express静态资源添加子路径前缀
    当前express.static直接挂载到根路径,既会和主应用的静态资源冲突,也无法匹配子路径的资源请求。需要修改为:

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

    这样当请求/secondappp/main.js时,Express才会去dist/secondappp/目录下查找对应文件。

  3. 调整路由匹配规则
    原路由app.get('/*')会拦截所有路径请求,包括主应用的路由,必须改成只匹配子应用路径:

    app.get('/secondappp/*', (req,res) => {
      res.sendFile(__dirname +'/dist/secondappp/index.html')
    });
    

    这样只有访问/secondappp下的路径时,才会返回子应用的index.html,避免干扰主应用。

  4. 重新构建子应用
    修改base href后,建议用命令重新构建,避免手动修改出错:

    ng build --base-href /secondappp/
    

    构建后的index.html会自动带上正确的base href,资源路径也会对应匹配。

修正后的完整代码

server.js

const express = require('express');
const http = require('http'); // 原代码写错了,将http当成https引入,此处修正

const app = express();
const port = 4000;

// 挂载子路径静态资源
app.use('/secondappp', express.static(__dirname + '/dist/secondappp/'));

// 处理子应用路由
app.get('/secondappp/*', (req,res) => {
  res.sendFile(__dirname +'/dist/secondappp/index.html')
});

const server = http.createServer(app);
server.listen(port, () => console.log('Server running on port 4000'));

构建后自动生成的index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <base href="/secondappp/">
  <meta content="width=device-width, initial-scale=1" name="viewport">
  <link href="favicon.ico" rel="icon" type="image/x-icon">
</head>
<body>
  <p>TESTING ANGULAR IN NODE JS</p>
<app-root></app-root>
</body>
</html>

内容的提问来源于stack exchange,提问作者idee programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:57:13