如何配置 Angular ng serve API 代理

例如,要将 /api 代理到 http://localhost:62232,首先在 package.json 所在的同一目录中创建 proxy.conf.json

proxy.conf.json
{
    "/api":
    {
        "target": "http://localhost:62232",
        "secure": false
    }
}

现在我们需要修改 package.json。找到调用 ng serve 的行,例如:

package.json
"start": "ng serve",

并将 --proxy-config proxy.conf.json 添加到 ng serve 的参数中:

package.json
"start": "ng serve --proxy-config proxy.conf.json",

package.jsonscripts 部分的完整示例:

package.json
"scripts": {
  "ng": "ng",
  "start": "ng serve --proxy-config proxy.conf.json",
  "build": "ng build --configuration=production",
  "watch": "ng build --watch --configuration development",
  "test": "ng test"
},

Check out similar posts by category: Angular, Javascript