SpringBoot前后端分离的跨域问题
前端报错:has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is
解决代码:
CorsConfig.java
@Configuration public class CorsConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { // TODO Auto-generated method stub // super.addCorsMappings(registry); registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(3600); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); //设置日期格式 ObjectMapper objectMapper = new ObjectMapper(); SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd"); objectMapper.setDateFormat(smt); mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper); //设置中文编码格式 List<MediaType> list = new ArrayList<MediaType>(); list.add(MediaType.APPLICATION_JSON_UTF8); mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list); converters.add(mappingJackson2HttpMessageConverter); super.configureMessageConverters(converters); } }
LoginFilter.java
@Component @ServletComponentScan @WebFilter() public class LoginFilter implements Filter { @Resource private OauthService oauthService; @Resource private SessionUtils tokenUtils; private String[] ignoreUrls = null; // 刷新患者的地址 private static final String IGNORE_URL = PropertiesBean.getInstance() .getProperty("rivamed.security.cas.app-pattern.ignoring"); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse response2 = (HttpServletResponse) response; response2.setHeader("Access-Control-Allow-Origin","*"); response2.setHeader("Access-Control-Allow-Credentials", "true"); response2.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response2.setHeader("Access-Control-Max-Age", "5000"); response2.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since," + " Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,Authorization,Token,tokenId,tokenid"); HttpServletRequest request2 = (HttpServletRequest) request; String tokenId = request2.getHeader("tokenId"); String method = request2.getMethod(); // Long startTime=System.currentTimeMillis(); for (String ignoreUrl : ignoreUrls) { if (request2.getRequestURI().contains(ignoreUrl)) { chain.doFilter(request, response2); return; } } if (UmConstants.CROSS_REQUEST_METHOD.equals(method)) { chain.doFilter(request, response2); return; } AccessToken token = oauthService.findAccessToken(tokenId); if (null != token) { if (token.tokenExpired() && token.refreshTokenExpired()) { writeResponse(response2, Constants.LOGIN_EXPIRED); return; } if (token.tokenExpired() && !token.refreshTokenExpired()) { writeResponse(response2, Constants.TOKEN_EXPIRED); return; } else { tokenUtils.initTokenUser(tokenId); chain.doFilter(request, response2); } } else { writeResponse(response2, Constants.LOGIN_EXPIRED); return; } // Long endTime=System.currentTimeMillis(); // System.out.println(request2.getRequestURI()+"---used time---"+(endTime-startTime)); } private void writeResponse(HttpServletResponse response2, String status) throws IOException { // HttpServletResponse response2 = (HttpServletResponse) response; OutputStream outputStream = response2.getOutputStream();// 获取 ExeceptionDto dto = new ExeceptionDto(); dto.setOpFlg(status); response2.setHeader("content-type", "application/json;charset=UTF-8");// 通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码 byte[] bs = JSONObject.toJSONBytes(dto, SerializerFeature.EMPTY); outputStream.write(bs);// 使用OutputStream流向客户端输出字节数组 } @Override public void init(FilterConfig filterConfig) throws ServletException { ignoreUrls = IGNORE_URL.split(","); } @Override public void destroy() { } }
原理:
前后端分离,后端用SpringBoot遇到的跨域问题
https://www.jianshu.com/p/a02500ef1446
⎛⎝官萧何⎠⎞一只快乐的爪哇程序猿;邮箱:1570608034@qq.com