개발자의 노트
반응형

참고: https://gist.github.com/kdonald/2232095


스프링에서 CORS 문제를 해결하기 위해 해당 Class를 하나 작성한다.


 

package com.xxxx.core.filter;


import java.io.IOException;


import javax.servlet.FilterChain;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.springframework.web.filter.OncePerRequestFilter;


public class CorsFilter extends OncePerRequestFilter {


    @Override

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)

            throws ServletException, IOException {

        response.addHeader("Access-Control-Allow-Origin", "*");

        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())); {

            // CORS "pre-flight" request

            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

            response.addHeader("Access-Control-Allow-Headers", "Authorization");

            response.addHeader("Access-Control-Max-Age", "1728000");

        }

        filterChain.doFilter(request, response);

    }


}



web.xml 에 아래 필터 추가


    <!-- CORS -->

    <filter>

        <filter-name>cors</filter-name>

        <filter-class>com.xxxx.core.filter.CorsFilter</filter-class>

    </filter>


    <filter-mapping>

        <filter-name>cors</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>


profile

개발자의 노트

@곽코딩

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!