I can do it(Feat. DEV)

[CORS] Axios 응답 객체에 Content-Disposition 누락 이슈 해결 본문

개발자 모드/오류처리

[CORS] Axios 응답 객체에 Content-Disposition 누락 이슈 해결

까짓거 해보자 개발자 2024. 2. 23. 17:47
728x90
📝글을 쓰게 된 계기

 

진행 중인 프로젝트 간단한 스펙 설명 

 - Spring Boot

 - TypeScript

 - Mybatis

 

엑셀 기능 개발 중 Axios 응답 객체에서 Content-Disposition을 찾을 수 없는 문제가 발생함.

 

분명히 아래 코드와 같이 서버단에서 응답 헤더에 파일명을 설정을 했는데

//파일명 인코딩
String encodedFilename = URLEncoder.encode(tblName+"목록","UTF-8");	
//헤더에 파일명 세팅
response.setHeader("content-disposition", "attachment; filename=\"" + encodedFilename + ".xlsx\"");
//콘텐츠 타입 설정
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

 

뷰단 react에서 찍어봐도 undefinded만 뜸. 당황🤦‍♂️

 

갓글에 검색해 보니 CORS 문제라는 것을 알게 됨.

 


 

🛠 해결방법

 

먼저 필자는 스프링 부트를 사용해서 서버를 구현했기 때문에 그에 따른 해결책을 기술하겠음.

 

갓글에 검색해보니 @CrossOrigin어노테이션을 통해 exposedHeaders 값으로 Content-Disposition 추가해서

 

해결하는 방법이 있었지만 필자는 

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")            
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Content-Disposition")	//추가할 구문
                .allowCredentials(true)
                .maxAge(3600);
    }
}

 

와 같이 addCorsMappings라는 메서드로 CORS 구성 설정을 하였고, allowedHeaders("*") 다음에

 

.exposedHeaders("Content-Disposition") 를 추가하면 response headers 객체에 content-disposition이 추가된 것을 확인할 수 있을 것임!!!🎉

 

추가적으로 위 구문 설명

 

- registry : CORS 구성을 적용할 URL 패턴을 설정하기 위한 CorsRegistry 객체
- addMapping() : CORS 규칙을 적용할 url 패턴을 지정
- allowedOrigins() : 허용된 출처(도메인)을 설정
- allowedMethods() : 허용된 HTTP 메서드를 설정
- allowedHeaders() : 허용된 HTTP 헤더를 설정
- allowCredentials() : 자격증명을 사용할지 여부 설정
- maxAge() : 사전 요청 결과를 캐시할 시간을 설정
- '*' 는 따로 설정하지 않고 전부 허용하겠다는 것

 

이상 끝!!🖐

 

📢참조 사이트

https://soobakba.tistory.com/30

 

axios로 파일 다운로드 및 Content-Disposition 정보 사용하기

파일 다운로드 기능을 구현하면서 약간의 삽질을 하면서 애를 먹었는데 덕분에 새로운 사실들을 알게 되었다. 서버에서 ByteArray 값을 내려주는 경우 파일로 만들어 내려받기 서버에서 response head

soobakba.tistory.com

 

728x90