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

如何将ng serve与ExpressJS配合运行以避免频繁重启?

当然可以!这里有两种常用方案帮你实现 ng serve 和 Express 配合,告别频繁重启服务器的麻烦

方案一:并行运行 ng serve 和 Express 服务

这种方法是让 Angular 的开发服务器(ng serve)和 Express 服务器同时运行,各自处理前端静态资源和 API 请求。

  1. 安装并行运行工具
    首先安装 concurrently 包,它能让你在同一个终端窗口里运行多个命令:

    npm install concurrently --save-dev
    
  2. 修改 package.json 的 scripts 配置
    更新你的 scripts,让 start 命令同时启动两个服务:

    "scripts": {
      "ng": "ng",
      "start": "concurrently \"ng serve\" \"node ./bin/www\"",
      "build": "ng build",
      "test": "ng test",
      "lint": "ng lint",
      "e2e": "ng e2e",
      "server": "node ./bin/www"
    },
    
    • ng serve 会默认在 4200 端口 启动 Angular 开发服务器,支持代码热重载
    • node ./bin/www 启动你的 Express 服务器(保持在 3000 端口)
  3. 处理跨域问题
    因为前端跑在 4200,API 跑在 3000,浏览器会有跨域限制。你需要在 Express 里添加 CORS 支持:
    先安装 cors 包:

    npm install cors --save
    

    然后在 Express 入口文件(比如 app.js)里引入并启用:

    const cors = require('cors');
    app.use(cors());
    
  4. 更新 Angular 的 API 请求地址
    确保你 Angular 代码里的 API 请求都指向 http://localhost:3000(比如 http://localhost:3000/api/items)。


方案二:使用 Angular 代理配置转发 API 请求

这种方法更优雅,让 ng serve 把 API 请求代理到 Express 服务器,不用处理跨域,前端请求直接写相对路径即可。

  1. 创建代理配置文件
    在 Angular 项目根目录下创建 proxy.conf.json 文件,内容如下:

    {
      "/api/*": {
        "target": "http://localhost:3000",
        "secure": false,
        "changeOrigin": true
      }
    }
    

    这个配置表示:所有以 /api 开头的请求,都会被转发到 http://localhost:3000。

  2. 修改 ng serve 命令
    更新 package.json 里的 scripts,让 ng serve 使用这个代理配置:

    "scripts": {
      "ng": "ng",
      "start": "concurrently \"ng serve --proxy-config proxy.conf.json\" \"node ./bin/www\"",
      "build": "ng build",
      "test": "ng test",
      "lint": "ng lint",
      "e2e": "ng e2e",
      "server": "node ./bin/www"
    },
    
  3. 简化 Angular 的 API 请求
    现在你 Angular 里的 API 请求可以直接写相对路径,比如 /api/items,ng serve 会自动把它转发到 http://localhost:3000/api/items,完全不用处理跨域。


额外优化:后端代码热重载

如果想让 Express 后端代码修改后也自动重启,可以安装 nodemon 包:

npm install nodemon --save-dev

然后把 server 命令改成:

"server": "nodemon ./bin/www"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:02:30