Liberty server.xml和CORS设置

时间:2018-02-07 01:46:37

标签: angular websphere-liberty server.xml open-liberty

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

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

  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.
    
  2. 响应标头

    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" />
      
    2. 错误:

      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允许来源。 有没有解决的办法? 感谢

1 个答案:

答案 0 :(得分: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 );
   }

`