官方网站:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#cors-configuration
测试跨域
第一步:在gateway添加user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div >
<table border="1">
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>age</th>
</tr>
</thead>
<tbody id="userlist">
</tbody>
</table>
</div>
<input type="button" value="用户列表" onclick="getData()">
<script>
function getData() {
$.get('http://localhost:8070/order/add',function(data){
alert(data)
});
}
</script>
</body>
</html>
第二步:测试
发现访问不了,因为跨域
解决跨域问题-配置文件方式
第一步:修改application.yml
server:
port: 8070
spring:
application:
name: api-gateway
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedMethods:
- GET
- POST
routes:
- id: order_route
uri: lb://order-service
predicates:
- Path=/order/**
filters:
- PrefixPath=/myorder
- CheckAuth=zhangsan
nacos:
discovery:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
第二步:测试
解决跨域问题-配置类方式
第一步:添加配置类
package com.example.gateway.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;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter(){
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**",config);
return new CorsWebFilter(source);
}
}
第二步:启动测试
|