Spring Boot + Angular项目中CORS跨域请求被拦截问题求助
Spring Boot + Angular项目中CORS跨域请求被拦截问题求助
大家好,我最近在做Spring Boot后端搭配Angular前端的项目时,遇到了CORS跨域拦截的问题,折腾好久都没解决,想请各位帮忙看看!
我遇到的错误提示如下:
Access to XMLHttpRequest at 'http://127.0.0.1:8082/api/cvs/recrutement' 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.
情况是这样的:用Postman调用Spring Boot的API完全正常,没有任何错误,但用Angular前端调用时,就会弹出上面这个blocked by CORS policy的错误。
下面是我的相关代码:
后端Spring Boot的Controller代码
@RestController @CrossOrigin(origins = "http://localhost:4200") public class CSVController { @Autowired CSVService fileService; @Autowired CandidatRepository dao; @GetMapping("/api/cvs/recrutement") @PreAuthorize("hasRole('RH') or hasRole('FINANCE') or hasRole('ADMIN')") public ResponseEntity<List<Candidat>> getAllCandidats() { try { List<Candidat> Candidats = fileService.getAllTutorials(); if (Candidats.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(Candidats, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } }
后端的CORS配置类
public class CorsConfig implements WebMvcConfigurer{ @Bean public WebMvcConfigurer corsConfigurer() { System.out.println("CORS Config success"); return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:4200"); // "/create-cars" } }; } }
Angular前端的组件代码(component.ts)
getAllCandidat() { this._dao.findAllCandidat().subscribe(resp=>{ this.ExcelData = resp }) }
Angular前端的服务代码
findAllCandidat() { return this.http.get<any[]>(`${BASIC_URL}api/cvs/recrutement`) }
有没有大佬能帮我看看问题出在哪呀?谢谢大家!
备注:内容来源于stack exchange,提问作者King Kapeta




