Customise ng serve to proxy calls to /api?

▼魔方 西西 提交于 2019-12-03 05:38:40

问题


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?

The Webpack dev server has a proxy setting, but it seems (?) ng serve doesn't have a config file (or I didn't get).

Do I need to create a webpack.config.js or create/edit some other file to proxy ?


回答1:


You can indeed setup a proxy to backend with the angular cli, with the --proxy-config flag.

Here is more or less a copy-paste from the documentation:

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 package.json called proxy.conf.json with the content

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

[...]

and then we edit the package.json file's start script to be

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

and run it with npm start



来源:https://stackoverflow.com/questions/42219277/customise-ng-serve-to-proxy-calls-to-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!