1

在 WebSphere Liberty 上,我有一个在https://localhost:9443/context-root/objects上运行的后端。它可以工作,我可以从浏览器或邮递员测试我的 REST API。

我使用 Visual Studio Code 在 Angular 中编写了一个 Web UI。当我尝试使用 Crome localhost:4200 使用 REST API 的 UI http 调用测试('> ng serve')时,我收到错误:

  1. 没有 CORS 设置的 server.xml

    The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
    

响应标头

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:origin, content-type, accept, authorization 
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin:*
Access_Control_Max_Age:43200
Cache-Control:no-store, no-cache=set-cookie
Content-Length:284
Content-Type:application/json
  1. 带有 CORS 设置的 server.xml

    <cors domain="/context-root"
      allowedOrigins="http://localhost:4200"
      allowedMethods="GET, DELETE, POST, PUT"
      allowedHeaders="accept"
      allowCredentials="true"
      maxAge="3600" />
    

错误:

Failed to load https://localhost:9443/context-root/objects: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4200, *', but only one is allowed. Origin 'http://localhost:4200' is therefore not allowed access.

响应标头:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:origin, content-type, accept, authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost:4200
Access-Control-Allow-Origin:*
Access_Control_Max_Age:43200 

我不确定为什么我在响应标头中得到双值,以及为什么特别是我得到 2 个允许来源。有没有解决的办法?谢谢

4

1 回答 1

0

从上面的评论到我的回答,解决方案出现了。
有一个 ContainerResponseFilter 类,它一直以编程方式添加 CORS 设置,无论它们是否在 server.xml 中设置。
因此,每个 REST API 调用都将它们包含在所有 Response 中。
我删除了过滤器类并解决了问题。谢谢你 :-)

`

@Override
   public void filter( ContainerRequestContext requestContext,
         ContainerResponseContext responseContext )
         throws IOException
   {
      final int ACCESS_CONTROL_MAX_AGE_IN_SECONDS = 12 * 60 * 60;
      MultivaluedMap<String, Object> headers = responseContext.getHeaders();
      headers.add( "Access-Control-Allow-Credentials", "true" );
      headers.add( "Access-Control-Allow-Headers",
            "origin, content-type, accept, authorization" );
      headers.add( "Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS, HEAD" );
      headers.add( "Access-Control-Allow-Origin", "*" );
      headers.add( "Access_Control_Max_Age",
            ACCESS_CONTROL_MAX_AGE_IN_SECONDS );
   }

`

于 2018-02-08T16:40:29.340 回答