[英]Angular and Spring boot: No 'Access-Control-Allow-Origin' header is present on the requested resource. How to solve it by angular and spring boot
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 ##错误:从源 'http://localhost:4200' 访问 XMLHttpRequest at 'http://localhost:8083/getuser' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access -Control-Allow-Origin' 标头存在于请求的资源上##
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 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";
}
}
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 ...如果这只是您正在使用的玩具项目而不是生产代码,您可以像这样禁用
CorsFilter
中的SpringSecurity
...
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable()...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.