Angular 4 http CORS No "Access-Control-Allow-Origin" with Java Servlet

I am trying to do http.post but chrome shows the following error:

No Access-Control-Allow-Origin.

My Angular function:

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 doPost method of my servlet 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");

      

+3


source to share


1 answer


If you still want to use CORS when developing, you can solve this problem using angular / cli --proxy-config .

Essentially if you want to make requests to a remote machine, for example on an nginx webserver, you execute all your calls to the same application, for example localhost:4200

(by default in angular / cli). Then you redirect those responses to your server with --proxy-config

.

Suppose you have all prefix entry points in your api server /api

. You need to create a file called proxy.config.json in your project root directory and configure it like this:

{
    "/api" : {
        "target" : "http://xx.xxx.xxx.xx", // Your remote address
        "secure" : false,
        "logLevel" : "debug", // Making Debug Logs in console
        "changeOrigin": true
    }
}

      

And then all your HTTP requests will point to localhost:4200/api/

.

Finally, you must do by executing ng server --proxy-config proxy.config.json

.

If you notice that some headers are missing from the request, add them from your web server or edit http.service.ts

to add the ones shown in this example:



import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { isNull } from 'lodash';

@Injectable()
export class HttpClientService {

  private _host: string;
  private _authToken: string;
  private _options: RequestOptions = null;

  constructor(private _http: Http, private _config: AppConfig, private _localStorageService: LocalStorageService) {
      this._host = ''; // Your Host here, get it from a configuration file
      this._authToken = ''; // Your token here, get it from API
  }

  /**
   * @returns {RequestOptions}
   */
   createAuthorizationHeader(): RequestOptions {
      // Just checking is this._options is null using lodash
      if (isNull(this._options)) {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
        headers.append('Authorization', this._authToken);
        this._options = new RequestOptions({headers: headers});
      }
      return this._options;
   }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    get(url?: string, data?: Object): Observable<any> {
      const options = this.createAuthorizationHeader();
      return this._http.get(this._host + url, options);
    }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    post(url?: string, data?: Object): Observable<any> {
      const body = JSON.stringify(data);
      const options = this.createAuthorizationHeader();
      return this._http.post(this._host + url, body, options);
    }

}

      

So you will be making all your api calls through this service, for example

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClientService } from './http.service.ts';

export class TestComponent implements OnInit {

  _observable: Observable<any> = null;

  constructor(private _http: HttpClientService) { }

  ngOnInit() {
      this._observable = this _http.get('test/')
                .map((response: Response) => console.log(response.json()));
  }

}

      

Angular 5 Update :

In app.module.ts

now you need to replace import { HttpModule } from '@angular/http';

with import { HttpClientModule } from '@angular/common/http';

.

The service will change slightly to:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { isNull, isUndefined } from 'lodash';

@Injectable()
export class HttpClientService {

  private _host: string;
  private _authToken: string;
  private __headers: HttpHeaders;

  constructor(private _http: HttpClient, private _config: AppConfig, private _localStorageService: LocalStorageService) {
      this._host = ''; // Your Host here, get it from a configuration file
      this._authToken = ''; // Your token here, get it from API
  }

  /**
   * @returns {HttpHeaders}
   */
   createAuthorizationHeader(): HttpHeaders {
      // Just checking is this._options is null using lodash
      if (isNull(this.__headers)) {
        const headers = new HttpHeaders()
           .set('Content-Type', 'application/json; charset=utf-8')
           .set('Authorization', this. _authToken || '');
        this.__headers= new RequestOptions({headers: headers});
      }

      return this.__headers;
   }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    get(url?: string, data?: Object): Observable<any> {
      const options = this.createAuthorizationHeader();
      return this._http.get(this._host + url, {
          headers : this.createAuthorizationHeader()
      });
    }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    post(url?: string, data?: Object): Observable<any> {
      const body = JSON.stringify(data);
      const options = this.createAuthorizationHeader();
      return this._http.post(this._host + url, body, {
          headers : this.createAuthorizationHeader()
      });
    }
}

      

+10


source







All Articles