-2

After all of this I am getting the same error . how to solve it.

error: Access to XMLHttpRequest at 'http://localhost:8083/getuser' from origin 'http://localhost:4200' 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 ##

Interceptor.ts

 @Injectable()
export class AuthInterceptor implements HttpInterceptor{

 constructor(private loginService:LoginService){

 }

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  let newReq=req;
  let token=this.loginService.getToken();
  console.log("Interceptor ",token) 

  if(token!=null){
    newReq=newReq.clone({setHeaders:{Authorization:`Bearer ${token}`}})
  }
  return next.handle(newReq)
}

}

app.module.ts

providers: [LoginService,AuthGuard, 
 [{provide:HTTP_INTERCEPTORS,useClass:AuthInterceptor,multi:true}]]

Backend controller

@CrossOrigin(origins ="*")
@RestController
public class Home {

@GetMapping("/welcome")  
public String welcome() {
    
    System.out.println("Home.welcome()");
    return "this is private page ";
}

@GetMapping("/getuser")
public String getUser() {
    
    return "My Name";
}
}
  • Check this solution https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – Ravi Korrapati Nov 07 '21 at 14:49
  • Unfortunately this error can mean many things. If your server is returning a successful response, it's likely that you're not returning CORS headers with the response. However, browsers assume requests are always successful so when an error occurs - which is a case where most servers do NOT return CORS headers by default - the browser will assume that it's a CORS issue rather than a server error. These can be difficult to debug but remember that it may not be CORS-related at all. – spork Nov 07 '21 at 15:41

1 Answers1

1

If this is just a toy project you are working with and not production code, you can just disable the CorsFilter in SpringSecurity like this ...

@EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().disable()...
        }
    }
Arthur Klezovich
  • 2,595
  • 1
  • 13
  • 17