title: Angular 6 accessing REST failing with Access-Control-Allow-Origin
body: <p>So I am trying to load the data from a REST source into my Angular 6 app using <code>http: HttpClient</code> from <code>'@angular/common/http'</code>. Calling the app in the browser using <code>ng serve --open</code> though doesn't do the job. I assume CORS to be the problem here. I guess I either have to set the server or the client headers with <code>Access-Control-Allow-Origin</code> or something, but I have already tried multiple ways without any success in making this simple REST call work. So what follows below is what I coded.</p>
  
  <p>Calling the Angular app in the browser responds the following error:</p>
  
  <pre><code>Failed to load http://localhost:8080/mysite-backend/rest/report/single/d83badf3: 
  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.
  </code></pre>
  
  <p>Calling the same URL (<code>http://localhost:8080/mysite-backend/rest/report/single/d83badf3</code>) within the Chrome browser works perfectly though:</p>
  
  <pre><code>{"id":"d83badf3","language":"en","categoryId":"a5","title":"Simcity","created":1527723183880,"modified":1527723183880}
  </code></pre>
  
  <p>Within Angular 6 I use the following service class that I generated with <code>ng generate service tour</code>. Within that I created the method <code>getTour(id: string)</code> which does non more than call REST at the URL and return the retrieved JSON-string as a Tour object:</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { HttpHeaders, HttpClient } from '@angular/common/http';
  import { Observable, of } from 'rxjs';
  import { Tour } from './tour';
  import { catchError, tap } from 'rxjs/operators';
  
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };
  
  @Injectable({
    providedIn: 'root'
  })
  export class TourService {
  
    // URL to the web api.
    private tourUrl = 'http://localhost:8080/mysite-backend/rest/report';
  
    constructor(
      private http: HttpClient
    ) { }
  
    /**
     * 
     * @param id: string GET tour report by id. Will 404 if id not found.
     */
    getTour(id: string): Observable&lt;Tour&gt; {
      httpOptions.headers.append('Access-Control-Allow-Origin', 'http://localhost:8080');
      httpOptions.headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
      httpOptions.headers.append('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
      httpOptions.headers.append('Access-Control-Allow-Credentials', 'true');
  
      const url = `${this.tourUrl}/single/${id}`;
      console.log("XXX URL GET " + url)
      return this.http.get&lt;Tour&gt;(url, httpOptions).pipe(
        tap(_ =&gt; this.log(`fetched tour id=${id}`)),
        catchError(this.handleError&lt;Tour&gt;(`getHero id=${id}`))
      );
    }
  
    private handleError&lt;T&gt; (operation = 'operation', result?: T) {
      return (error, any): Observable&lt;T&gt; =&gt; {
        console.error(error);
        this.log(`${operation} failed: ${error.message}`);
        return of(result as T);
      };
    }
  
    private log(message: string) {
      console.log("Log message: " + message);
    }
  }
  </code></pre>
  
  <p>This is the <code>Tour</code> object:</p>
  
  <pre><code>export class Tour {
      id: string;
      language: string;
      categoryId: string;
      created: Date;
      modified: Date;
      title: string;
      content: string;
  }
  </code></pre>
  
  <p>I also added <code>HttpClientModule</code> from <code>'@angular/common/http'</code> to the <code>imports</code> array and the <code>providers</code> array within <code>app.module.ts</code>.</p>
  
  <p>The RESTful WebService is built in Java. Here I have the <code>getReport(@PathParam("reportId") String reportId)</code> method, that gets an <code>Report</code> object and returns it within a <code>Reponse</code>:</p>
  
  <pre><code>import java.util.List;
  import javax.inject.Inject;
  import javax.servlet.http.HttpServletRequest;
  import javax.ws.rs.Consumes;
  import javax.ws.rs.DELETE;
  import javax.ws.rs.GET;
  import javax.ws.rs.POST;
  import javax.ws.rs.PUT;
  import javax.ws.rs.Path;
  import javax.ws.rs.PathParam;
  import javax.ws.rs.Produces;
  import javax.ws.rs.core.Context;
  import javax.ws.rs.core.MediaType;
  import javax.ws.rs.core.Response;
  
  /**
   * Describes the RESTful access for reports.
   */
  @Path("/report")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public class ReportResource {
      @Inject
      private Logger logger;
  
      @GET
      @Path("/single/{reportId}")
      public Response getReport(@PathParam("reportId") String reportId) {
          //return Mock.getReport(reportId);
          return Response.ok() // 200
                         .entity(Mock.getReport(reportId))
                         .header("Access-Control-Allow-Origin", "*")
                         .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                         .allow("OPTIONS").build();
      }
  ...
  }
  </code></pre>
  
  <p>What must I do to make a successful call from the Angular 6 client to the Java RESTful WebService?</p>