1

I'm try to build an app using Angular 5 through Webstorm. I have set up my services at back end. When i am trying to retrieve data from postman or from Rest client tool that Webstorm provide everything is ok.

But when i try to get data from my actual code of typescript angular says

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 

I have add headers at the backend on my java service such as

        response.addHeader("Access-Control-Allow-Origin", "*"); 
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

My fuction at export class is below

      constructor(private http: HttpClient) { }




  login(username: string, password: string) {
    console.log(username + '' + password);
    const headers = new HttpHeaders().append('Content-Type', 'application/json')
    const url  = 'http://localhost:8080/../UserLogin';



    return this.http.post(url, {'username': username, 'password': password}  )
      .subscribe(
      (data: any) => {
        console.log(data);

      }
    );

  }

When i check the request Headers from Network Session of chrome i see that the request method is options and there is nowhere the request data.

I am kind confused about why postman and the rest client of webstrom run nice instead of my function and the second one about the request method which convert from Post to OPTIONS

Any help would be appreciate.

Dimitris
  • 133
  • 2
  • 13

2 Answers2

1

You need to add { withCredentials: true } as the third parameter of your post.

return this.http.post(
    url,
    {'username': username, 'password': password},
    { withCredentials: true }
  )
  .subscribe(
    (data: any) => {
      console.log(data);
    }
  );
machinehead115
  • 1,647
  • 10
  • 20
  • Thanks for you direct answer. I tried your implemention but still get the same error. As i see from post documentation the third param refers to options. I also try to add my headers such as return this.http.post(url, {'username': username, 'password': password} , { headers : headers} ) .subscribe( (data: any) => { console.log(data); but still the same. } ); – Dimitris Apr 27 '18 at 19:45
0

The actual issue rely on how Chrome evaluate CORS operations.

I find that answer from a relative post that really helps me

No 'Access-Control-Allow-Origin' header is present on the requested resource error

If you install that extension everything returns back to normal :

Chrome Extension

3 wasted hours for an extesion :P

Dimitris
  • 133
  • 2
  • 13