本篇文章只是个人记录
问题描述:
在做微服务的项目的时候, 访问gateway的时候发生了跨域问题
基础打的不牢固唉!
项目描述:
gateway+nacos+springbootWeb
gateway项目端口:9020
服务端 端口: 9001
springboot2.7.6
gateway怎么样做跨域配置都没用, 前端在访问gateway的时候都是报错跨域错误.
然后我觉得是不是9001端口的问题, 然后我又给,9001端口做了跨域配置,结果怎么样弄还是不行
傻乎乎的我以为, gateway和服务端都要做上跨域问题,后来发现只要gateway做好跨域配置就好了
问题就出在, 我在给9020和9001都做了跨域了,然后一直报错options请求被拒绝
以下是我的gateway跨域配置:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedMethods: "*"
allowedHeaders: "*"
allowedOriginPatterns: "*"
allowCredentials: true
下面是我的另外一个问题了,比较古怪吧
在使用WebMvcConfigurer 全局跨域配置时不生效
package com.headnews.admin.userservice.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;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author HFQ
* @version 1.0.0
* @ClassName CorsConfig.java
* @Description TODO
* @createTime 2024年01月10日 10:46:00
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//是否发送Cookie
.allowCredentials(true)
//放行哪些原始域
.allowedOrigins("*")
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
.allowedHeaders("*")
.exposedHeaders("*");
}
}
但, 我换了一种方式使用拦截器的方式去配置跨域,跨域请求进来了,这是为什么?
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsConfig 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-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}
有厉害的大佬知道是为什么吗