【发布时间】:2019-04-05 11:17:45
【问题描述】:
我在端口 4202 中为 angular 应用程序提供服务,并通过以下代码连接到删除 spring mvc 应用程序。
this.http.post<Hero[]>('http://localhost:8080/api/hero/list', {"id":1}, httpOptions)
但它报告了以下错误。
Failed to load http://localhost:8080/api/hero/list: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4202' is therefore not allowed access. The response had HTTP status code 403.
所以我尝试通过控制器方法中的以下注释在我的 Spring Web 应用程序中启用 cors。
@CrossOrigin(origins = "http://localhost:4202")
我还尝试添加如下配置类。
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
然后我刷新我的前端 ui,如下所示。
Failed to load http://localhost:8080/api/hero/list: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4202, *', but only one is allowed. Origin 'http://localhost:4202' is therefore not allowed access.
然后我检查了我的 chrome 网络,如下所示,它确实重复了“Access-control-allow-origin”头。
然后我用谷歌搜索了很多,发现其他人遇到了这个问题,因为 Tomcat 前面的其他 Web 服务器生成了第二个“Access-control-allow-origin”头。但是我只有一个tomcat服务器,除了'ng serve'启动的服务器。
然后我尝试通过 fiddler 而不是 angular 直接访问这个 url(http://localhost:8080/api/hero/list)。下面是截图,我可以发现没有重复的“Access-Control-Allow-Origin”。
所以我猜测是不是由angular启动的nodejs服务器引起的?由于我是 Angular 的新手,我不知道如何看待这个问题。谢谢。
【问题讨论】:
-
由于您在 Angular HttpClient 中使用 localhost:8080/api... 进行调用,因此不要通过本地 Angular CLI 开发服务器。你直接进入你的 Spring 端点。所以它一定是服务器端的问题。作为旁注,我通常不执行 CORS 请求,而是在我的 Angular CLI 开发服务器上使用代理配置,以避免在后端执行 CORS。我有一篇关于它的文章,如何设置它:juristr.com/blog/2016/11/configure-proxy-api-angular-cli
标签: angular spring-mvc angular7