Angular 4 http CORS No 'Access-Control-Allow-Origin' with a java servlet

Viewed 29805

I'm trying to do a http.post but chrome is showing the following error:

No Access-Control-Allow-Origin.

My Angular function is:

onSubmit(event: Event) {
  event.preventDefault();
    this.leerDatos()
    .subscribe(res => {
      //datos = res.json();
      console.log("Data send");
    }, error => {
          console.log(error.json());
      });



  }

  leerDatos(): Observable<any> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(`http://localhost:8080/LegoRepositoryVincle/CoreServlet`, { name: "bob" }, options)
                    //.map(this.extractData)
                    //.catch(this.handleError);
  }

And my servlet doPost method includes:

response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.addHeader("Access-Control-Allow-Origin","http://localhost:4200");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Methods","GET,POST");
response.addHeader("Access-Control-Allow-Headers","X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Pragma");
2 Answers

You may use Angular CLI proxy tooling for this purpose.

  • 1. you create a file proxy.config.json at the root of your project
  • 2. you map your API URLs to target URLs using this syntax
 "/api/xxxxxxx" : {
        "target" : "http://www.api.com/xxxxxxx", 
        "secure" : false,
        "logLevel" : "debug",
        "changeOrigin": true
    }
  • 3. Serve your application using
ng serve --proxy-config proxy.config.json
Related