简体   繁体   English

是否可以在angular-cli中更改“ ng serve”配置(我想添加一些规则,因此一些请求将被重定向到另一个端口)?

[英]Is it possible to change `ng serve` config in angular-cli (i want to add some rule, so some requests will be redirected to another port)?

I am creating small Angular 2 + TypeScript example. 我正在创建小的Angular 2 + TypeScript示例。 Here is the code. 是代码。

I need some really simple backend stub now. 我现在需要一些非常简单的后端存根。 What I want to do. 我想做的事。 I want to create expressjs server on localhost:3000 for example. 我想例如在localhost:3000上创建expressjs服务器。 And I want to modify ng serve config, so if I ask localhost:4200/api/x/y/z this request will be redirected to localhost:3000/x/y/z . 我想修改ng serve config,所以如果我问localhost:4200/api/x/y/z此请求将重定向到localhost:3000/x/y/z

What I want to achieve? 我想实现什么? This will allow me to make http request to /api/x/y/z in my Angular application. 这将允许我在Angular应用程序中向/api/x/y/z发出http请求。 Web server will make redirect to express backend. Web服务器将进行重定向以表示后端。 Express will handle and generate some json etc. Express将处理并生成一些json等。

Why I don't want to just make request to localhost:3000/x/y/z ? 为什么我不想只向localhost:3000/x/y/z发出请求? As I remember there will be some problems because of CORS. 我记得由于CORS会出现一些问题。

May be there is another way to achieve what I want? 可能还有另一种方式可以实现我想要的吗? Any thoughts? 有什么想法吗?

--proxy-config options is the answer --proxy-config选项就是答案

  1. Add cli-profy.conf.json with this contents: 添加具有以下内容的cli-profy.conf.json

    { "/api": { "target": " http://localhost:3000/ ", "secure": false } } {“ / api”:{“目标”:“ http:// localhost:3000 / ”,“安全”:假}}

  2. Change start script to this: ng serve --open --proxy-config cli-proxy.conf.json start脚本更改为: ng serve --open --proxy-config cli-proxy.conf.json

  3. Run npm start . 运行npm start

Now all requests to localhost:4200/api/ will be passed to localhost:3000/api . 现在,所有对localhost:4200/api/请求都将传递到localhost:3000/api

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM