1.配置文件解决跨域
使用Filter方式进行设置
@Slf4j @Component public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; HttpServletRequest httpRequest = (HttpServletRequest) request; httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader(HttpHeaders.ORIGIN)); httpResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); httpResponse.setHeader("Access-Control-Max-Age", "3600"); httpResponse.setHeader("Access-Control-Allow-Headers", "*, Authorization, Origin, User-Agent, Referer, Accept, Content-type, languageType, Cache-Control, Pragma, Expires"); chain.doFilter(request, response); } @Override public void destroy() { } }
2.使用注解解决接口跨域
使用 @CrossOrgin 注解
@CrossOrigin可以使用在类上面,也可以使用在接口上面
@CrossOrigin @PatchMapping("/v1/{id}") public Response update(@RequestBody @Valid Request<ReqVO> reqVORequest, @PathVariable Long id, HttpServletRequest httpServletRequest) {
}
3. Nginx配置解决跨域
#跨域配置 # add_header 'Access-Control-Allow-Origin' '*'; #允许来自所有的访问地址 # add_header 'Access-Control-Allow-Credentials' 'true'; # add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS'; #支持请求方式 # add_header 'Access-Control-Allow-Headers' 'Content-Type,Access-Control-Allow-Headers,Authorization,X-Requested-With';
标签:Control,Access,java,跨域,跨越,Allow,解决,httpResponse,public From: https://www.cnblogs.com/eternality/p/16892494.html