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