SpringBoot通過CORS解決前端跨域問題

1. 問題表現(xiàn)

如果前后端代碼部署在不同的服務(wù)器上,或者同一個服務(wù)器的不同端口上,前端去請求后端數(shù)據(jù)就有跨域問題。
端口不一樣也是跨域,也會有CORS disable問題。

2. 前端的調(diào)試小記

(1) CORS調(diào)試

右鍵,檢查,console

如果是跨域,這里會寫,你被CORS阻止了。

(2) 正常端口調(diào)試

右鍵,檢查,network

這里面就會有各種發(fā)送的請求以及響應(yīng)。

3. 跨域問題解決

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

如果是直接訪問,springboot的某一個接口,直接通過端口號去訪問,這種只涉及到一個接口的跨域設(shè)置,可以在這個接口上打注解。

(2) springcloud gateway跨域設(shè)置

根源在Webflux上邊,由于gateway使用的是webflux,而不是springmvc,所以需要先關(guān)閉webflux的cors,再從gateway的filter里邊設(shè)置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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容