본문 바로가기

Spring

Front 에서 Http 통신하는데 Access to XMLHttpRequest at' ~ ~ ~ ' from origin '~ ~ ~' has been blocked by CORS policy 에러!!!!

에러문장


Access to XMLHttpRequest at 'http://localhost:8080/api/boards' 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.

 


해결방법


 

백엔드서버에서 해주는 응답에  다음헤더 넣어주기

HttpHeaders headers = new HttpHeaders();

headers.set("Access-Control-Allow-Origin", "*");
headers.set("Access-Control-Allow-Methods","GET,POST,OPTIONS,DELETE,PUT");

headers.set("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");

    @GetMapping("/")
    public ResponseEntity<?> findAll() throws Exception {

         HttpHeaders headers = new HttpHeaders();
         headers.setContentType(new MediaType("text","xml", Charset.forName("UTF-8")));
         headers.set("Access-Control-Allow-Origin", "*");
         headers.set("Access-Control-Allow-Methods","GET,POST,OPTIONS,DELETE,PUT");

         return ResponseEntity.status(HttpStatus.OK).headers(headers).body("응답이에요");
       
     }

 


또는

 

 

 

백엔드의 Controller에  다음과 의 어노테이션으로  프론트 서버 정보 입력해주기.


@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class BoardController {
   
    @CrossOrigin(origins = "http://localhost:4200")
    @GetMapping("/boards")
    public ResponseEntity<?> findAll() throws Exception {
            return ResponseEntity.status(HttpStatus.OK).body(listBoard);
        
   }

    
}