1
    @Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', "dassda")
    });
    console.log(authReq);
    return next.handle(authReq);
  }
}

any tutorials on Internet use this code to add Authorization header in a request, in my situation if I set header, all other headers are deleted.

Error : "Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource".

but if I delete line headers: req.headers.set('Authorization', "dassda") always is ok

console.log(req.headers) returns map(0)

I'm trying:

  • hardcode all headers- error anywhere

  • trying to use all methods in req.headers like append, setHeaders, Headers

  • append headers like "Access-Control-Allow-Origin/headers/methods" and etc -create new headers,

  • download google plugin Moesif Origin & CORS Changer that program add all needed headers to all requests- then write error "has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

Abhishek Duppati
  • 610
  • 6
  • 18
Vlad
  • 13
  • 4
  • try req = req.clone({ headers: req.headers.set('Authorization', "dassda") }); instead of using a const use req object – LogicBlower May 21 '20 at 20:23

2 Answers2

0

You can use like this, it's a shortcut way to add new headers during clone.

request = request.clone({
  setHeaders: {
    Authorization: `Bearer ${token}`
  },
});

https://stackoverflow.com/a/45221680/2681943

Nikhil Walvekar
  • 510
  • 3
  • 9
0

problem was on my Backend(Java), i pasted this code into my config method and everything worked fine.

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
Vlad
  • 13
  • 4