自定义 ng serve 以代理对/api 的调用? [英] Customise ng serve to proxy calls to /api?

查看:15
本文介绍了自定义 ng serve 以代理对/api 的调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 ng CLI 创建了一个新应用程序,它的工作原理非常棒:<代码>ng新的babystepscd 婴儿舞步服务ng serve 使用 webpack 来组装应用程序.为了完全测试它,我需要从我的 API 模拟服务器(特别是 POST 请求)提供 /api... 服务.如何自定义使用的 Web 服务器以重定向该 URL 模式?

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 标志设置代理以使用 angular 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.

我们在项目 package.json 旁边创建一个名为 proxy.conf.json 的文件与内容

We create a file next to projects package.json called proxy.conf.json with the content

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

[...]

然后我们将package.json文件的启动脚本编辑为

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

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

并使用 npm start

这篇关于自定义 ng serve 以代理对/api 的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆