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

查看:122
本文介绍了自定义ng服务以代理对/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.

我们在项目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服务以代理对/api的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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