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

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

spring:application:name: service-getwaycloud:gateway:globalcors:cors-configurations:'[/**]':# 允许携带认证信息# 允许跨域的源(网站域名/ip),设置*为全部# 允许跨域请求里的head字段,设置*为全部# 允许跨域的method, 默认为GET和OPTIONS,设置*为全部# 跨域允许的有效期allow-credentials: trueallowed-originPatterns: "*"allowed-headers: "*"allowed-methods:- OPTIONS- GET- POSTmax-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); }}

再然后在编写一个配置类
@Configurationpublic class WebFilterConfig {@Beanpublic 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-gatewaycloud:nacos:discovery:server-addr: localhost:8848gateway:globalcors:corsConfigurations:'[/**]':allowedHeaders: "*"allowedOrigins: "*"allowCredentials: trueallowedMethods:- GET- POST- DELETE- PUT- OPTION

最后需要注意一点,既然是在网关里边来解决跨域问题的,就不能在下流的服务里边再重复引入解决跨域的配置了。
否则会导致跨域失效,报跨域的问题。
【gateway网关与前端请求跨域问题的解决方案】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读