Angular CLI具有development proxy configuration option,可用于拦截对开发后端的调用并将其路由到API。这可以让您独立完成项目并利用@angular/cli
工具。
您会在与angular-cli.json
文件相同的级别创建一个名为proxy.conf.json
的文件。比方说,在发展的节点API端口在http://localhost:3000
运行,你的API端点所有下路径“/ API”的proxy.conf.json
内容看起来像:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
您可以设置为根据需要进行很多拦截,在这种情况下,它只会拦截对“/ api”所做的调用,并将它们引导至运行在http://localhost:3000
的项目。
这样,你会需要修改npm start
在角app命令的package.json
利用代理:
"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
和我的角应用程序位于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)
希望帮助!
您是否使用[Angular CLI](https://github.com/angular/angular-cli)创建Angular项目? –
是的,我正在使用Angular CLI –