定制 ng serve 以代理调用 /api?

40
我使用ng CLI创建了一个新的应用程序,非常好用: ng new babysteps cd babysteps ng serve ng serve使用webpack来组装应用程序。为了完全测试它,我需要从我的API模拟服务器(特别是POST请求)服务于/api...。我该如何自定义所使用的Web服务器,以重定向那个URL模式?
Webpack dev server有代理设置,但似乎(?) ng serve没有配置文件(或者我没找到)。
我需要创建一个webpack.config.js文件或者创建/编辑其他文件来代理吗?

我相信你所要求的是代理配置。请查看Angular-CLI文档中的这个部分 - alex kucksdorf
1个回答

86

您可以使用Angular CLI的--proxy-config标志来设置代理到后端。

以下内容基本上是从文档中复制粘贴而来:

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


1
如果你正在运行一个 Express 后端和 Webpack 构建,可以同时使用 watch 运行后端和前端的 ng serve... "dev": "concurrently "ng serve --proxy-config proxy.conf.json" "webpack --watch" "nodemon dist/server/app.bundle.js"" - Michael Dausmann
@@Michael Dausmann@@ 非常感谢。我过去几天一直在努力设置这个。这是一个绝妙的提示。 - kaluva
@MichaelDausmann 我一直在尝试查看如何使用代理配置监视文件。我认为你回答了我一直在寻找的内容,但是我没有理解你的评论:(。这方面有文档吗? - Joshua JLIVE Williams
@JoshuaJLIVEWilliams 同时运行两个任务可以使用 concurrently (https://www.npmjs.com/package/concurrently)。第一部分与接受的答案相同,第二部分来自 webpack (https://webpack.js.org/configuration/watch/)。 - Michael Dausmann
针对从 Azure 服务的 API,需要设置 "changeOrigin": true。请参考 https://github.com/webpack/webpack-dev-server/issues/424#issuecomment-333452471。 - Radek
如果需要,您甚至可以重写URL。只需在“secure”下方添加第三个属性“pathRewrite”:{ "^/api": "" },则对于http://localhost:4200/api的请求将被重写为http://localhost:3000(而不是http://localhost:3000/api)@see https://webpack.js.org/configuration/dev-server/#devserverproxy - Humppakäräjät

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接