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

Node.js服务器部署Angular构建产物报错求助

问题分析与解决方案

你的问题核心在于Angular的base href配置与Express的路由/静态文件服务不匹配,导致浏览器无法正确加载Angular的静态资源,甚至把HTML文件当成JS解析。下面一步步拆解问题并给出修复方案:

为什么会出现这些错误?

第一个错误(404找不到资源)

你构建后的index.html里设置了<base href="/angular-app/">,当你通过http://localhost:3000/angular访问应用时,浏览器会根据base href拼接资源路径,比如去请求http://localhost:3000/angular/angular-app/runtime.js——但你的dist文件夹里根本没有angular-app子目录,自然会返回404。

第二个错误(Unexpected token <)

当你改成app.get('*')后,所有请求(包括runtime.js、polyfills.js这些静态资源请求)都会返回index.html。浏览器拿到HTML文件却试图把它当成JS解析,就会报Unexpected token <(因为HTML的第一个字符是<)。


修复步骤

1. 调整Angular的base href

因为你期望通过/angular路径访问应用,所以需要把base href设置为/angular/:

  • 方式一(推荐):重新构建Angular应用时指定base href
    ng build --base-href /angular/
    
  • 方式二:直接修改dist/index.html里的<base>标签
    <base href="/angular/">
    

2. 修改Express的server.js配置

需要让Express知道:

  • /angular路径下的静态资源对应dist文件夹
  • 所有/angular下的子路由都返回index.html(支持Angular的路由跳转)

修改后的server.js代码:

const express = require('express');
const path = require('path');
const http = require('http');
const app = express();

// 将静态文件服务挂载到'/angular'路径,对应dist文件夹
app.use('/angular', express.static(path.join(__dirname, 'dist')));

// 捕获所有/angular下的路由,返回index.html(支持Angular单页应用路由)
app.get('/angular/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

const port = process.env.PORT || '3000';
app.set('port', port);

const server = http.createServer(app);
server.listen(port, () => console.log(`API running on localhost:${port}`));

验证修复

  1. 重启你的Express服务器
  2. 访问http://localhost:3000/angular,此时浏览器会正确请求http://localhost:3000/angular/runtime.js等资源,应用就能正常加载了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:21:22