Reza
Reza

Reputation: 543

CORS in angular using tomcat

I have my own angular 5 project, I have an HTTP interceptor Component for adding auth in the header for all request, and also I have a service to call custom server API. when I use HTTP, my rest service works fine (of course I added cors filter in my tomcats's web.xml) but my HTTP interceptor Component does not catch it, but when I use httpClient it goes throw HTTP interceptor Component but the server response is "No 'Access-Control-Allow-Origin' header is present on the requested resource". would you please help me?

    import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

import { Http, Headers, Response, RequestOptions, RequestMethod } from 
'@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const API_URL = environment.apiUrl;

@Injectable()
export class RestService {

constructor(private http: HttpClient) { }

private handleError (error: Response | any) {
console.error('ApiService::handleError', error);
return Observable.throw(error);
}


public getAll(input: any, url: string): Observable<any> {

return this.http
  //.get('http://httpbin.org/headers')
  .post(API_URL + url, input)
  .map(response => {
    const returnedData = response;
    return returnedData;
  })
  .catch(this.handleError);
}

}

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } 
from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';


@Injectable()
export class HttpinterceptorComponent implements HttpInterceptor {
constructor() { }

intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {

console.log('intercepted request ... ');

const headers = new HttpHeaders({
  'sessionId': 'token 123',
  'Content-Type': 'application/json'
});


// Clone the request to add the new header.
const authReq = req.clone({headers});

console.log('Sending request with new header now ...');

// send the newly created request
return next.handle(authReq)
.catch((error, caught) => {
  // intercept the respons error and displace it to the console
  console.log('Error Occurred');
  console.log(error);
  // return the error to the method that called it
  return Observable.throw(error);
}) as any;
}
}

Upvotes: 1

Views: 2685

Answers (2)

Reza
Reza

Reputation: 543

after weeks finally found the solution, if you are using Spring MVC in your backend you can enable CORS Filter by extending WebMvcConfigurerAdapter, without any server configuration

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

   @Override
   public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**");
   }
}

and also put CorsOrigin on your Controller or your specific method

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)

CORS support in Spring Framework

Enabling Cross Origin Requests for a RESTful Web Service

Upvotes: 0

Mike Tung
Mike Tung

Reputation: 4821

In your tomcat filter you need to add the following and propagate the configuration changes.

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Upvotes: 1

Related Questions