Skip to content

ng serve: support for proxy urls #889

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
reppners opened this issue May 23, 2016 · 55 comments
Closed

ng serve: support for proxy urls #889

reppners opened this issue May 23, 2016 · 55 comments
Labels
effort2: medium (days) feature Issue that requests a new feature P5 The team acknowledges the request but does not plan to address it, it remains open for discussion

Comments

@reppners
Copy link
Contributor

At development time our teem needs to proxy AJAX-requests with urls that match certain patterns/regexes to a different machine running the application backend.

Is this use-case already covered but not yet documented by ng serve?

If not I would like to propose this as a feature:

  • pass an array of strings/regexes to ng serve
  • if any of those strings/regexes match the url of the request then proxy the request to a configurable ip/port

If this however is not in the scope of ng serve, what benefits would our team lose if we were NOT using ng serve in the dev-workflow at all?

@dmnk89
Copy link

dmnk89 commented May 25, 2016

try --proxy http://127.0.0.1:8080

this is from ember-cli and it worked in some previous version

@filipesilva
Copy link
Contributor

We haven't done such functionality no. If you find it working within ember-cli options, please reply here for other people with the same issue.

@filipesilva filipesilva added feature Issue that requests a new feature command: serve labels May 25, 2016
@fatsu
Copy link

fatsu commented May 26, 2016

Using --proxy http://host:port/context works out-of-the-box with IE & Chrome.

To get it working in Firefox (38), I had to explicitly set the 'Accept' request header to '*/*'.
The call was forwarded, but as the returned response content-type was not in the default accept headers, the index.html was returned instead.

e.g.:

this.http
      .get('/some/api', { headers: new Headers({'Accept' : '*/*' }) })

You could ofcourse also set it to the explicit content type you would be expecting e.g. 'application/json'.

Also, you can set the DEBUG environment variable to * before calling ng serve to get server debugging info. This slows down the server a lot.

SET DEBUG=*
ng serve --proxy http://host:port/context

@bastienJS
Copy link

@fatsu @filipesilva Is it possible to save the proxy url somewhere in the angular-cli.json so it is always considered when I just do ng serve ?

@filipesilva filipesilva added effort2: medium (days) P5 The team acknowledges the request but does not plan to address it, it remains open for discussion labels Jun 4, 2016
@bastienJS
Copy link

@filipesilva @dmnk89 seems I did not read what you wrote about the ember-cli file. So I tried to put this in the ember-cli file:

{
   "output-path": "../TGB.Web/wwwroot", // for asp.net core backend
   "proxy": "http://localhost:33333"
}

That works fine!

Of courseits confusing at first time why use ember inside angular... but well it works!

@hantsy
Copy link

hantsy commented Jul 3, 2016

@bastienJS Angular CLI is based on Ember CLI.

But, how to configure multi proxies?

eg.

/api for http://api.example.com
/mgt/ for https://example2.com/management

@filipesilva
Copy link
Contributor

@bastienJS I'm glad you found a way to persist it! It's counter-intuitive but at least it works for now.

@unrevised6419
Copy link

unrevised6419 commented Jul 6, 2016

In my case worked this way
Install ember using
npm install -g ember-cli
create file ember-cli-build.js in root folder with this content

/*jshint node:true*/
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
  var app = new EmberApp(defaults, {});
  return app.toTree();
};

Now you can use

ember generate server
ember generate http-mock
ember generate http-proxy

to generate server, mocks and proxys for angular project, and it works
These commands are listed when ng help generate or ember help generate is entered. There you can see more info!
image

@filipesilva
Copy link
Contributor

I'd like to mention that with #1455, the native ember-cli support for proxies probably doesn't work anymore.

@mmrath
Copy link
Contributor

mmrath commented Jul 28, 2016

@filipesilva any idea/hack to get this working? I have full backend API available, I am developing an alternate client using ng2. So proxy option is very helpful to me for quick demo and testing.

@filipesilva
Copy link
Contributor

@TheLarkInn is there any simple way to have this with the webpack dev server?

@TheLarkInn
Copy link
Member

TheLarkInn commented Jul 28, 2016

Webpack dev server configuration includes support for proxy.

https://webpack.github.io/docs/webpack-dev-server.html#proxy

We already have a dev server configuration object used here that we would need to simply tie the commandsOptions and apply to that config.

Proxy setup was a little out of my wheelhouse so we left it open for those interested to PR or tackle after we cut a release.

@mmrath hopefully this would give you a starting point if you wanted to submit a PR for it!! 👏

@mmrath
Copy link
Contributor

mmrath commented Jul 28, 2016

@TheLarkInn, @filipesilva thanks. I'll give it a go today.

I am thinking of adding an option --proxy-config with argument to file path relative to project. The file can contain all the options available to webpack dev server which will be passed as is by clicking. I think this will allow lot of flexibility for cases like multiple proxy, URL rewrite etc. Do you think this is an acceptable approach?

@TheLarkInn
Copy link
Member

It sounds awesome!! If we implement it is like to see tests to verify that proxies are working (however it's done). Go ahead and make a PR and we can discuss the implementation from there.

@ankeshdave
Copy link

ankeshdave commented Jul 29, 2016

@mmrath while you are implementing proxy options if possible try to add support for using proxy behind a Corporate Firewall. See issue ember-cli/ember-cli#6032

This option does not work on ember-cli and I personally was not able to figure out , which options to use for node http-proxy module in the ProxyMiddleware of ember-cli. I hope webpack could support the same.

@unrevised6419
Copy link

Someone tried solution I added above?
#889 (comment)

@mmrath
Copy link
Contributor

mmrath commented Jul 29, 2016

@iamandrewluca now that cli moved to webpack, I am in favor of an webpack-y solution.

@mmrath
Copy link
Contributor

mmrath commented Aug 2, 2016

@TheLarkInn when you have a moment, could you review PR#1487?

@filipesilva
Copy link
Contributor

Closed by #1487

@filipesilva
Copy link
Contributor

Big thanks to @mmrath for adding this functionality!

@llstarscreamll
Copy link

I have spent a lot of time searching how to make work the proxy settings, finally this worked for me:

proxy.conf.json

{
  "/api/*": {
    "target": "http://test.dev",
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug"
  }
}

The important part is "changeOrigin": true. More info here:
webpack/webpack-dev-server#458

@michaeljpeake
Copy link

michaeljpeake commented Dec 7, 2016

Hooray!
"changeOrigin": true made everything work how I expected. Reading the link shared by @llstarscreamll, this seems to be required when using nginx. Thanks!

@jquince
Copy link

jquince commented Dec 16, 2016

I am running a hybrid app and am having problems with deep linking.
I started out with https://github.com/AngularClass/angular2-webpack-starter and was able to get things working using the bypass function for proxy configuration.

I am moving to Angular-cli and now it seems bypass is not a supported option.
Http://localhost:4200/myapp/mydashboard is returning 404 but should return myapp/index.html

@sumigoma
Copy link

sumigoma commented Dec 23, 2016

doesn't angular2-webpack-starter achieve this with the webpack-dev-server option historyApiFallback: true? I am having the same problem and would like ng serve to reroute to index.html on a 404 (by default out of the box), as all SPAs will have this requirement.

@alperg
Copy link

alperg commented Jan 10, 2017

None of the above solutions but this worked for me:

{
  "/api": {
    "target": "http://jsonplaceholder.typicode.com/",
    "changeOrigin": true,
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    },
    "logLevel": "debug"
  }
}

@chriseenberg
Copy link

chriseenberg commented Jan 16, 2017

For those looking, unable to get these proxy's to work, what did it for me was i forgot the http infront of localhost:8080

Working solution looks like this
{ "/api/*": { "target": "http://localhost:8080", "changeOrigin": true, "secure": false, "logLevel": "debug" } }
the important part here being http-prefix :)
Hope this helps.

@rkrzewski
Copy link

The proxy works great, but is there a way to put proxy configuration into .angular-cli.json, so that it's automatically applied each time ng serve is invoked?
I tried adding

"serve": {
  "proxy": {
    "config": "./proxy.conf.json"
  }
}

section to .angular-cli.json by analogy to "test" section but it has no effect. I also tried searching for a reference page for available settings in .angular-cli.json but came back empty handed.

I also tried searching open issues but I wasn't able to find anything relevant. Should I file a feature request?

@dmnk89
Copy link

dmnk89 commented Feb 21, 2017

I am not aware of any other way than described above.
As a walkaround we added in package.json

  "scripts": {
    "start": "ng serve --proxy-config proxy.conf.json"
   }

and start it with npm start

@hantsy
Copy link

hantsy commented Mar 29, 2017

I encountered the similar issues as @michaeljpeake, the proxy config does not work in my case.

The backend is a nodejs application, served at port 3000. The frontend is NG 2 application generated by Angular CLI.

I added a proxy.conf.json in the root of frontend application.

{
  "/api/*": {
    "target": "http://localhost:3000",
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug"
  }
}

and changed the start command in package.json. I also tried the simplest config in the Wiki page(proxy to backend, it does not work).

 "start": "ng serve --port 4300 --proxy-config proxy.conf.json",

When I run the application, I got error messages from cmd console.

[HPM] GET /api/upload/uploads-1490782788752.png -> http://localhost:3000
[HPM] Error occurred while trying to proxy request /api/upload/uploads-1490782788752.png from localhost:4300 to http://localhost:3000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)

The image should be accessed via http://localhost:4300/api/upload/uploads-1490782788752.png, but failed, and it is existed at http://localhost:3000/api/upload/uploads-1490782788752.png

When I accessed http://localhost:4300/api/upload/uploads-1490782788752.png, in Chrome browser. It displays a message:

Error occured while trying to proxy to: localhost:4300/api/upload/uploads-1490782788752.png

When access http://localhost:3000/api/upload/uploads-1490782788752.png, it displays the image directly.

My local development environment:

  1. Node
node -v
v7.7.4
  1. npm
npm -v
4.1.2
  1. NG 1.0.0
ng -v
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.0.0
node: 7.7.4
os: win32 x64
@angular/common: 2.4.10
@angular/compiler: 2.4.10
@angular/core: 2.4.10
@angular/forms: 2.4.10
@angular/http: 2.4.10
@angular/platform-browser: 2.4.10
@angular/platform-browser-dynamic: 2.4.10
@angular/router: 3.4.10
@angular/cli: 1.0.0
@angular/compiler-cli: 2.4.10

@parthivreddy27
Copy link

var api = proxyMiddleware('/api', {
target: 'https://applications.tst.ngi.com',
secure: false,
onProxyReq: function (proxyReq, req, res) { //line: 05
//console.log("Setting custom proxy headers"); //line: 06
proxyReq.setHeader('X-USF-RESPONSE-URL', 'https://192.xxx.xxx.xxx/svc/auth/sagl'); //line: 07
proxyReq.setHeader('X-GUI-URL', 'https://192.xxx.xxx.xxx/'); //line: 08
}
});

the above code is in angular 1.x
i want to write same code in angular cli project. I am able to add proxy as below:
{
{
"/api": {
"target": "https://applications.tst.ngi.com",
"secure": false,
"logLevel": "debug"
}
}

Help me to add headers to proxy as above from line number 05 to 08

@tc9011
Copy link

tc9011 commented May 11, 2017

None of the above solutions but this worked for me:

{
  "/api/*": {
    "target": "http://10.63.246.83:2017/api",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": "http://10.63.246.83:2017/api"
    }
  }
}

But there is a problem with this solution, when the proxy address changes, I need to change two places.

Hope to have a better solution

@tc9011
Copy link

tc9011 commented May 16, 2017

I have solved my own problem

Now proxy.conf.json is:

{
  "/API": {
    "target": "http://10.63.246.83:2017",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

http request is :

this.http.get('/API/subsystem')...........

@ghost
Copy link

ghost commented May 16, 2017

Please excuse my ignorance, as I am fairly new to angular. Does the proxy.config.json work when building and deploying to iis?

@mmrath
Copy link
Contributor

mmrath commented May 16, 2017 via email

@ghost
Copy link

ghost commented May 16, 2017

@mmrath Ok awesome, thanks.

@Rithie
Copy link

Rithie commented Jun 25, 2017

I've noticed that sometimes even with this proxy server set correctly, I got some erros. What I've realized that the issue was on my request (usually with PUT and POST). I passed a bad request at some point, then I got a reverse
IP related to my NG localhost.
{
"/api/*": {
"target": "http://localhost:3000",
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}

@guehmann
Copy link

guehmann commented Jul 4, 2017

Hy everybode, perhaps someone can help me, hope so.

I tried all the above issues but did not get a positive result.
My situation is as following:

  • have an web front angular2/4 running with 'ng serve'. everything went ok since a turned on authentication on the web api. could call the api hosted on an iis

  • the web.api is hosted on an iis as a virtual application under 'default web site'

after i turned on "windows authentication" on the web api i get the following errors on chrome console.
image

I tried all the issues about 'proxy-config' but nothing helped for me, perhaps I doing something wrong?

Front-End is running under localhost:4200 and the IIS-WebApi ist running under localhost/Anytime.WebServices/v1.2/controller/method on port 80

If i make a build with ng build --prod i do not get any errors.

So, hope someome can help me, thanks in advance.
Regards Jens.

@ankeshdave
Copy link

ankeshdave commented Jul 5, 2017

@guehmann
For Ntlm /negotiate I use the following configuration, mind it for some typos as I wrote it on a phone. You need to add agentkeepalive package in package.json

@filipesilva just a suggestion, This configuration is pretty standard for webpack-dev-server and can be added to proxy docs for windows auth.

var agent = require('agentkeepalive');
var kAgent = new agent({
    maxSockets: 100,
    keepAlive: true,
    maxFreeSockets: 10,
    keepAliveMsecs: 1000,
    timeout: 60000,
    keepAliveTimeout: 30000 // free socket keepalive for 30 seconds
});
var onRes = function (proxyRes, req, res) {
    var key = 'www-authenticate';
    proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',');
};

const CONFIG = [
    {
        context: [
            "/api"
        ],
        target: "http://192.168.1.101:80",
        secure: false,
        logLevel: 'debug',
        auth: 'LOGIN:PASS', //no need to put actual
        agent: kAgent,
        onProxyRes: onRes,
        changeOrigin: true
    }
]

module.exports = CONFIG  

@guehmann
Copy link

guehmann commented Jul 5, 2017

@ankeshdave
Hi, thank you for your response.

But i didn't get it to work. I put your code in a file name proxy.conf.js and substitute the following with my values:

"/api" -> "/v1.2" and
"http://192.168.1.101:80" -> "http://localhost:80/Anytime.WebServices"

my WebApi-method is reachable under http://localhost/Anytime.WebServices/v1.2/base/department/many

then i run: ng serve --proxy-config proxy.conf.js
even i get:
10% building modules 2/2 modules 0 active[HPM] Proxy created: [ '/v1.2' ] -> http://localhost:80/Anytime.WebServices
[HPM] Subscribed to http-proxy events: [ 'proxyRes', 'error', 'close' ]

the error is still the same, i changed localhost to the ip address and also the hostname, nothing happend. error is:

zone.js:2263 GET http://localhost/Anytime.WebServices/v1.2/base/department/many 401 (Unauthorized)
and
XMLHttpRequest cannot load http://localhost/Anytime.WebServices/v1.2/base/department/many. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

But CORS is fully enabled on any address, port and header on my WebApi.
On Postman-tool from Google my Api is working.

Perhaps you see my error.
Thanks in advance.
Regards Jens.

@ankeshdave
Copy link

@guehmann there is something not configured with your CORS configuration you first need to get that working, I am also using CORS (tomcat as server) and windows authentication from LDAP, this configuration works, Also try putting

/Anytime.WebServices/v1.2

in place of

/1.2

@guehmann
Copy link

guehmann commented Jul 6, 2017

@ankeshdave Thank for your reply. So I'll check what is wrong with my WebApi. I tried your issue with changing to /Anytime... but the result was the same.
I don't know, if i make a ng build and deploy it the the iis i do not get any errors with cors.

My WebApi is an asp.net core configured cors as follows.

// CORS kofigurieren
services.AddCors(options =>
options.AddPolicy("AllowAny", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Content-Disposition") // refused to get unsafe header error message
.AllowCredentials()));

and then
// CORS anwenden...
app.UseCors("AllowAny");

I'll try to fix it an give response.

Thank you very much.
Regards Jens.

@guehmann
Copy link

@ankeshdave Hi, I solved it with turning on anonymous authentication on the iis application. Now i can run the same WebApi with 'serve' and 'build' without any errors. Not even i need the proxy option. Thanks.

@Dev-Pawar
Copy link

Dev-Pawar commented Aug 14, 2018

suppose your proxy file is proxy.conf.json
{
"/api/*": {
"target": "http://localhost:3000", // your server url:port
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}

after you have to edit package.json file and add "start": "ng serve --proxy-config proxy.conf.json" in first braces where your project name, version available, so your new code looks like

{
"name": "neosuite-client",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
}

main part start here, you have to start your application like npm start.
After add the proxy file restart application by npm start.

and even you want to change the port then just add "start": "ng serve --port 5000 --proxy-config proxy.conf.json"

@truginis
Copy link

@Dev-Pawar this only works for me if I use HashLocation strategy, does not work with PathLocation. Any ideas?

@Dev-Pawar
Copy link

I think you have used ** RouterModule.forRoot(routes, {useHash: true}) ** , jusr try it by removing {useHash: true}, as by default angular support PathLocationStrategy. so you can use like

RouterModule.forRoot(routes) try this. hope it will work.

@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Sep 8, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
effort2: medium (days) feature Issue that requests a new feature P5 The team acknowledges the request but does not plan to address it, it remains open for discussion
Projects
None yet
Development

No branches or pull requests