💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
参考:https://cloud.tencent.com/developer/article/1668879 课件代码:https://gitee.com/flymini/codes02/tree/master/cors_/com-learn-cors01 **** 从后端解决跨域访问,总结如下几种解决方案,采用其中任意一种即可。 <br/> **1. 在 controller 层采用注解`@CrossOrigin`** ```java @RestController @CrossOrigin //将注解用在类上或方法上 public class VideoController { @PostMapping(value = "/demo") public Json demo(HttpServletRequest request, HttpServletResponse response) { System.out.println("...demo..."); } } ``` <br/> **2. 实现方法`addCorsMappings`** ```java @Configuration public class DemoConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") //允许访问 /** .allowedOrigins("*") //允许跨域访问 .allowedMethods("GET", "POST") //允许以GET、POST方法访问 .allowedHeaders("*") //允许任意请求头访问 .allowCredentials(true); } } ``` <br/> **3. 在过滤器中配置允许跨域访问** ```java @Component @WebFilter public class CorsFilter implements Filter { @Override 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", "*"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } } ``` <br/> **4. 在拦截器中配置允许跨域访问** (1)实现拦截器接口。 ```java @Component public class CustomHandlerInterceptorAdapter extends HandlerInterceptorAdapter { @Override public 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; } } ``` (2)注册拦截器到环境中。 ```java @Configuration public class CustomWebMvcConfigurer implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new CustomHandlerInterceptorAdapter()); } } ``` <br/> **5. 通过网关访问** 允许跨域访问网关,然后由网关去访问想要的服务。 ```yml spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allow-credentials: true #允许跨域的源(网站域名/ip),设置*为全部 allowed-origins: - "http://xb.abc.com" - "http://sf.xx.com" allowed-headers: "*" #允许跨域的method,默认为GET和OPTIONS,设置*为全部 allowed-methods: - OPTIONS - GET - POST - DELETE - PUT - PATCH max-age: 3600 ``` >[warning]注意: 通过 gateway 转发的其他项目,不要再进行跨域配置。