SpringBoot通过CORS解决前端跨域问题

1. 问题表现

如果前后端代码部署在不同的服务器上,或者同一个服务器的不同端口上,前端去请求后端数据就有跨域问题。
端口不一样也是跨域,也会有CORS disable问题。

2. 前端的调试小记

(1) CORS调试

右键,检查,console

如果是跨域,这里会写,你被CORS阻止了。

(2) 正常端口调试

右键,检查,network

这里面就会有各种发送的请求以及响应。

3. 跨域问题解决

(1) 加注解,每个都加,@CrossOrigin

如果是直接访问,springboot的某一个接口,直接通过端口号去访问,这种只涉及到一个接口的跨域设置,可以在这个接口上打注解。

(2) springcloud gateway跨域设置

根源在Webflux上边,由于gateway使用的是webflux,而不是springmvc,所以需要先关闭webflux的cors,再从gateway的filter里边设置cors就行了。

package net.youqu.micro.service.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * description:
 *
 * @author wangpeng
 * @date 2019/01/02
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}

配置yaml:

spring:
  cloud:
    gateway:
      discovery:
      # 跨域
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedHeaders: "*"
            allowedOrigins: "*"
            allowedMethods:
            - GET
              POST
              DELETE
              PUT
              OPTION
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容