Angular CLI 有一个development proxy configuration option,可用于拦截对开发后端的调用并将它们路由到 API。这可以让您独立处理项目并利用@angular/cli 工具。
您将创建一个名为 proxy.conf.json 的文件,该文件与您的 angular-cli.json 文件处于同一级别。假设您在开发中的节点 API 在 http://localhost:3000 的端口 3000 上运行,并且您的 API 端点在路径“/api”下 all,proxy.conf.json 的内容看起来喜欢:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
您可以根据需要设置任意数量的拦截,在这种情况下,它只会拦截对“/api”的调用并将它们定向到在http://localhost:3000 运行的项目。
然后您需要在 angular app 命令的package.json 中修改 yournpm start 以使用代理:
"scripts": {
...
"start": "ng serve --proxy-config proxy.conf.json",
...
},
然后您只需要在不同的命令窗口中分别运行后端和前端。您可以使用 concurrently 之类的库在开发中使用单个 npm start 运行多个命令。您将在基本节点 API 项目中设置 npm start 命令,如下所示:
"scripts": {
"start": "concurrently \"./bin/www\" \"cd public && npm start\"",
}
在此示例中,我的节点(快速)应用程序是从 ./bin/www 激活的,而我的 Angular 应用程序位于 public 文件夹中,但根据您的项目结构,这显然可能是不同的文件夹。如果后端节点 api 只是一个单一的条目文件 "start": "concurrently \"node ./server.js" \"cd public && npm start\"",那么你的开始可能会更简单。
示例结构:
Project
server.js (back-end node API)
package.json (concurrently library and command added here)
public (angular front-end app)
src
.angular-cli.json
package.json (npm start updated to use proxy)
proxy.conf.json (proxy configuration goes here)