0

I am developing an application using Angular 2 and I find the following error when I try to make an API call:

XMLHttpRequest cannot load http://localhost:9090/conf. 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:5555' is therefore not allowed access.

Here, there are two examples of my calls:

import { Http, Response } from '@angular/http';

// ...

@Injectable()
export class ConfService {

  // ...

  getConf(): Observable<string[]> {
    return this.http.get(
                      'http:localhost:9090/conf?id=1',
                      {
                        headers: {
                          'Accept': 'application/json;charset=UTF-8'
                        }
                      }
                    )
                    .map((res: Response) => res.json())
                    .catch(this.handleError);
  }

  setConf(conf: any[]): Observable<string[]> {
    return this.http.get(
                      'http:localhost:9090/conf?id=1',
                      conf,
                      {
                        headers: {
                          'Content-Type': 'application/json;charset=UTF-8'
                        }
                      }
                    )
                    .map((res: Response) => res.json())
                    .catch(this.handleError);
  }

}

However, when I use cURL it works!

$ curl -XPUT 'localhost:9090/configuration?id=1' \
> -H 'Content-Type: application/json'
> -d '{"conf":1234}'
Success!
$ curl -XGET 'localhost:9090/conf?id=1'
{"conf":1234}

What is happening here?

Thanks

1

1 Answer 1

3

It's because of browser security, a general CORS issue in browser. Your web app is running at localhost:5050 and server at localhost:9090. Browser won't allow to access another host with different port number. The solution is handle the CORS in your server (i.e in your app running at localhost:9090)

Sign up to request clarification or add additional context in comments.

2 Comments

My Spring app uses Tomcat and I cannot boot it if there is another app (my Angular client) using the same port.
Of course, they have to run in different port. Configure your spring app to have CORS headers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.