自定义ng服务以代理对/api的调用? [英] Customise ng serve to proxy calls to /api?
问题描述
我使用ng CLI创建了一个新应用程序,其工作原理很像:
ng new babysteps
cd babysteps
ng serve
ng serve使用webpack组装应用程序.为了对其进行全面测试,我需要从我的API模拟服务器(特别是POST请求)提供/api...
.如何定制用于重定向该网址格式的Web服务器?
I created a new application with ng CLI, works like a charm:
ng new babysteps
cd babysteps
ng serve
ng serve uses webpack to assemble the app. To fully test it, I need to serve /api...
from my API mock server (specifically the POST requests). How can I customise the web server used, to redirect that one URL pattern?
Webpack开发服务器具有代理设置,但似乎(?)ng serve
没有配置文件(或者我没有得到).
The Webpack dev server has a proxy setting, but it seems (?) ng serve
doesn't have a config file (or I didn't get).
我是否需要创建webpack.config.js
或创建/编辑其他文件以进行代理?
Do I need to create a webpack.config.js
or create/edit some other file to proxy ?
推荐答案
您确实可以通过--proxy-config
标志将代理设置为带有cli的后端.
You can indeed setup a proxy to backend with the angular cli, with the --proxy-config
flag.
这里或多或少是
假设我们有一台服务器运行在 http://localhost:3000/api 上,我们想要
对 http://localhost:4200/api 的所有调用以转到该服务器.
Say we have a server running on http://localhost:3000/api and we want
all calls to http://localhost:4200/api to go to that server. 我们在项目 We create a file next to projects [...] ,然后将 and then we edit the 并使用 这篇关于自定义ng服务以代理对/api的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
package.json
旁边创建一个名为proxy.conf.json
的文件
内容package.json
called proxy.conf.json
with the content{
"/api":
{
"target": "http://localhost:3000",
"secure": false
}
}
package.json
文件的开始脚本修改为package.json
file's start script to be"start": "ng serve --proxy-config proxy.conf.json"
npm start