一对一视频聊天源码,Java实现跨域方式
package org.chuancey.config;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter;@Configuration public class GlobalCorsConfig {@Beanpublic CorsFilter corsFilter() {//1. 添加 CORS配置信息CorsConfiguration config = new CorsConfiguration();// 放行哪些原始域config.addAllowedOrigin("*");// 是否发送 Cookieconfig.setAllowCredentials(true);// 放行哪些请求方式config.addAllowedMethod("*");// 放行哪些原始请求头部信息config.addAllowedHeader("*");// 暴露哪些头部信息config.addExposedHeader("*");//2. 添加映射路径UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**",config);//3. 返回新的CorsFilterreturn new CorsFilter(corsConfigurationSource);}}
package org.chuancey.config;import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**")//放行哪些原始域.allowedOrigins("*").allowedHeaders("*")// 是否发送Cookie.allowCredentials(true).allowedMethods("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH").maxAge(3600);}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");} }
在控制器(类上)上使用注解 @CrossOrigin,表示该类的所有方法允许跨域。
@RestController @CrossOrigin(origins = "*") public class VerificationController {}
在方法上使用注解 @CrossOrigin
@PostMapping("/check/phone")@CrossOrigin(origins = "*")public boolean checkPhoneNumber(@RequestBody @ApiParam VerificationPojo verification) throws BusinessException {return false;}
使用 HttpServletResponse 对象添加响应头(Access-Control-Allow-Origin)来授权原始域,这里 Origin的值也可以设置为 “*”,表示全部放行。
@RequestMapping("/home") public String home(HttpServletResponse response) {response.addHeader("Access-Allow-Control-Origin","*");return "home"; }
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component;@Slf4j @Configuration @WebFilter(filterName = "accessFilter", urlPatterns = "/*") public class MyCorsFilter implements Filter {public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) res;response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");chain.doFilter(req, res);}public void init(FilterConfig filterConfig) {log.info("AccessFilter过滤器初始化!");}public void destroy() {} }
xml使自定义Filter生效方式
<!-- 跨域访问 START--> <filter><filter-name>CorsFilter</filter-name><filter-class>org.chuancey.filter.MyCorsFilter</filter-class> </filter> <filter-mapping><filter-name>CorsFilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping> <!-- 跨域访问 END -->
spring: cloud:gateway:globalcors:cors-configurations:'[/**]':# 允许跨域的源(网站域名/ip),设置*为全部# 允许跨域请求里的head字段,设置*为全部# 允许跨域的method, 默认为GET和OPTIONS,设置*为全部allow-credentials: trueallowed-origins:- "http://xb.abc.com"- "http://sf.xx.com"allowed-headers: "*"allowed-methods:- OPTIONS- GET- POST- DELETE- PUT- PATCHmax-age: 3600
注意: 通过gateway 转发的其他项目,不要进行配置跨域配置
有时即使配置了也不会起作用,这时你可以根据浏览器控制的错误输出来查看问题,如果提示是 response 中 header 出现了重复的 Access-Control-* 请求头,可以进行如下操作
import java.util.ArrayList; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono;@Component("corsResponseHeaderFilter") public class CorsResponseHeaderFilter implements GlobalFilter, Ordered {@Overridepublic int getOrder() {// 指定此过滤器位于NettyWriteResponseFilter之后// 即待处理完响应体后接着处理响应头return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1;}@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {return chain.filter(exchange).then(Mono.defer(() -> {exchange.getResponse().getHeaders().entrySet().stream().filter(kv -> (kv.getValue() != null && kv.getValue().size() > 1)).filter(kv -> (kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)|| kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)|| kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)|| kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)|| kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_MAX_AGE))).forEach(kv -> {kv.setValue(new ArrayList<String>() {{add(kv.getValue().get(0));}});});return chain.filter(exchange);}));} }
location / {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Headers X-Requested-With;add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;if ($request_method = 'OPTIONS') {return 204;} }
@Component public class CrossInterceptor extends HandlerInterceptorAdapter {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "*");response.setHeader("Access-Control-Allow-Credentials", "true");return true;} }
以上就是一对一视频聊天源码,Java实现跨域方式, 更多内容欢迎关注之后的文章