启动应用程序:
@SpringBootApplication
@EnableZuulProxy
public class ZuulServer {
public static void main(String[] args) {
new SpringApplicationBuilder(ZuulServer.class).web(true).run(args);
}
}
我的 YAML 文件是这样的:
server:
port:8080
spring:
application:
name: zuul
eureka:
client:
enabled: true
serviceUrl:
defaultZone: http://localhost:8761/eureka/
zuul:
proxy:
route:
springapp: /springapp
我有一个名为 springapp 的微服务应用程序(在端口 8081 上)并有一些休息服务。下面是我的客户端 UI 应用:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="js/libs/jquery/jquery.min.js" ></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
url: 'http://localhost:8080/zuul/springapp/departments',
type: 'GET'
}).done(function (data) {
consoe.log(data);
document.write(data);
});
</script>
</body>
</html>
但我得到了一个
XMLHttpRequest cannot load http://localhost:8080/zuul/springapp/departments. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8383' is therefore not allowed access.
此 UI HTML5 应用位于 http://localhost:8383/SimpleAPp/index.html . CORS,CORS,CORS ...请帮助。顺便说一句http://localhost:8080/zuul/springapp/departments在浏览器地址栏上返回一个 json 列表。 spring.io 博客 here说不需要过滤器,因为 zuulproxy 负责处理,但我不知道为什么它对我不起作用。
最佳答案
将这段代码添加到使用 @EnableZuulProxy 注释的类中应该可以解决问题。
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
关于java - Spring Cloud - Zuul 代理正在生成 No 'Access-Control-Allow-Origin' ajax 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28670640/