0

I have this code:

client (angular2) hosted on this url:

http://localhost:8080/Me/html/pages/gasolina/country/USA

code:

  return this.http
          .post(this.supporToolSaveUrl, gasConfigModel, {headers: headers})
          .map(res => res.json())
          .subscribe(
            data => {
              console.info("next: ");
              console.info(data)
            },
            err => console.error(err)
          );

server (java jersey)

hosted on this url:

http://localhost:8080/Me/services/countries

code:

 @Path("/SaveConfig")
    @POST
    @Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
    @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
    public void saveConfig(CountryGasStationConfig countryGasStationConfig) throws Exception {

should i add these in jersy annotation?

When i run locally i get this error:

MLHttpRequest cannot load http://locahost:8080/.... Response for preflight is invalid (redirect)

I saw this post and this post

How can i make this solution in angular2?

app.

config(['$httpProvider', function ($httpProvider) {
  //Reset headers to avoid OPTIONS request (aka preflight)
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
}]);
Community
  • 1
  • 1
Elad Benda2
  • 9,463
  • 23
  • 67
  • 138
  • Why don't you just handle CORS correctly on the server if you control the server, instead of trying to resort to some client side hack. – Paul Samsotha Sep 24 '16 at 01:08
  • i don't want to allow CROS for all sites, how would you suggest to solve this in the server side? The client and server share the same domain, it should have not throw CROS error anyway – Elad Benda2 Sep 24 '16 at 12:17

1 Answers1

0

Your java server has CORS requests disabled. Changing your requests on the client side will not work, because OPTIONS requests are automatically created when requesting a server on another URL (even if it's just a different port on localhost). There's no way you can get around this.

Instead, you should enable CORS on your java server. Here's a tutorial for java jersey that also goes into details about what CORS is.

Federico Pettinella
  • 1,390
  • 1
  • 10
  • 17
  • but the client and the server have the same url including http protocol and same port. – Elad Benda2 Sep 24 '16 at 12:18
  • I have edited my q, showing the client and server have the same url. btw if you say fixing the client won't help - how come it's the accepted answer in the other SF post in my question body? – Elad Benda2 Sep 24 '16 at 12:33
  • Because that's particular to AngularJS, aren't you asking for a solution in Angular2? Maybe your url isn't correct like in http://stackoverflow.com/questions/38716357/angular2-response-for-preflight-is-invalid-redirect-from-some-get-requests – Federico Pettinella Sep 24 '16 at 12:44