软件编程
位置:首页>> 软件编程>> java编程>> gateway网关与前端请求跨域问题的解决方案

gateway网关与前端请求跨域问题的解决方案

作者:锦瑟思年华  发布时间:2022-09-20 01:30:44 

标签:gateway,网关,请求,跨域

gateway网关与前端请求的跨域问题

最近因项目需要,引入了gateway网关。可是发现将前端请求的端口指向网关后,用postman发送请求是正常的,用浏览器页面点击请求会出现跨域问题。今天就记录一下自己是怎么解决的。

第一种

直接在yml文件中配置


spring:
 application:
   name: service-getway
 cloud:
   gateway:
     globalcors:
       cors-configurations:
         '[/**]':
           # 允许携带认证信息
           # 允许跨域的源(网站域名/ip),设置*为全部
           # 允许跨域请求里的head字段,设置*为全部
           # 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
           # 跨域允许的有效期
           allow-credentials: true
           allowed-originPatterns: "*"
           allowed-headers: "*"
           allowed-methods:
             - OPTIONS
             - GET
             - POST
           max-age: 3600

允许跨域的源(网站域名/ip),设置*为全部,也可以指定ip或者域名。

第二种

写一个WebCrossFilter过滤器实现Filter,在doFilter方法中这样编写


public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
       HttpServletResponse res = (HttpServletResponse)response;
       HttpServletRequest req = (HttpServletRequest)request;
       res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
       res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
       res.setHeader("Access-Control-Max-Age", "3600");
       res.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
       res.setHeader("Access-Control-Allow-Credentials", "true");
       if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
           res.setStatus(HttpStatus.OK.value());
       } else {
           filterChain.doFilter(request, response);
       }
   }

再然后在编写一个配置类


@Configuration
public class WebFilterConfig {
   @Bean
   public FilterRegistrationBean webCrossFilterRegistration() {
       FilterRegistrationBean registration = new FilterRegistrationBean();
       registration.setFilter(new WebCrossFilter());
       registration.addUrlPatterns("/**");
       registration.addInitParameter("paramName", "paramValue");
       registration.setName("webCrossFilter");
       return registration;
   }
}

将WebCrossFilter注册到spring容器中,这样就解决了跨域问题。

建议在网关写了cross后,服务就不需要再写了。

gateway网关统一解决跨域

网上有很多种解决跨域问题的,只有这种用起来最简单。

通过修改配置文件的方式来解决

只需要在 application.yml 配置文件中添加红色框的配置:

gateway网关与前端请求跨域问题的解决方案


spring:
 application:
   name: app-gateway
 cloud:
   nacos:
     discovery:
       server-addr: localhost:8848
   gateway:
     globalcors:
       corsConfigurations:
         '[/**]':
           allowedHeaders: "*"
           allowedOrigins: "*"
           allowCredentials: true
           allowedMethods:
             - GET
             - POST
             - DELETE
             - PUT
             - OPTION

最后需要注意一点,既然是在网关里边来解决跨域问题的,就不能在下流的服务里边再重复引入解决跨域的配置了。

否则会导致跨域失效,报跨域的问题。

来源:https://blog.csdn.net/qq_40011778/article/details/115937727

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com