Maven 构建 web.xml 中的 Access-Control-Allow-Origin 标头设置

Posted

技术标签:

【中文标题】Maven 构建 web.xml 中的 Access-Control-Allow-Origin 标头设置【英文标题】:Access-Control-Allow-Origin header setup in Maven build web.xml 【发布时间】:2016-11-05 06:33:54 【问题描述】:

当我使用 jQuery 访问 REST 时,出现以下错误

XMLHttpRequest cannot load http://localhost:8185/Profile-iris/Profile.svc/GB0010001/enqEnqUserProfiles()?alt=json.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.

我了解我需要在服务器上设置 Access-Control-Allow-Origin。

下面是服务器端'web.xml'

<filter>
    <filter-name>cross-origin</filter-name>
    <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
    <init-param>
        <param-name>allowedOrigins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>allowedMethods</param-name>
        <param-value>GET,POST,DELETE,PUT,HEAD</param-value>
    </init-param>
    <init-param>
        <param-name>allowedHeaders</param-name>
        <param-value>origin,content-type,accept,authorization,maxdataserviceversion</param-value>
    </init-param>
</filter>
....
....
<filter-mapping>
    <filter-name>cross-origin</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Jboss 日志看起来不错。

16:21:37,872 INFO  [STDOUT] 11:51:37.872 [HDScanner] DEBUG
o.e.jetty.servlets.CrossOriginFilter - Cross-origin filter 
configuration: allowedOrigins = *, 
allowedMethods = GET,POST,DELETE,PUT,HEAD, 
allowedHeaders = origin,content-type,accept,authorization, maxdataserviceversion, 
preflightMaxAge = 1800, 
allowCredentials = true,
exposedHeaders = ,
chainPreflight = true

jQuery 客户端

    <script>
        $(document).ready(function() 
            $.ajax(
                url: "http://localhost:8185/Profile-iris/Profile.svc/GB0010001/enqEnqUserProfiles()?alt=json",
                type: "GET",
                dataType : "json",

                success: function(data)
                    console.log(data);
                ,
                error: function(error)
                    console.log(error);
                
            )
        );
    </script>

根据我的理解,上面的设置看起来是正确的。但是,我得到了同样的错误。谁能帮帮我。

【问题讨论】:

【参考方案1】:

当您在本地环境中工作时,有时会发生这种情况。如果是这样,那么您可以只使用 Google Chrome 扩展程序:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

安装它打开并忘记本地环境中的此错误消息。

【讨论】:

谢谢。我安装并启用了,但现在我收到XMLHttpRequest cannot load http://localhost:8185/Profile-iris/Profile.svc/GB0010001/enqEnqUserProfiles()?alt=json. Response for preflight has invalid HTTP status code 401 有什么建议吗?? HTTP 401 -> UNAUTHORIZED 请求我不认为这两个问题是相同的。 401 可能是不同的问题。

以上是关于Maven 构建 web.xml 中的 Access-Control-Allow-Origin 标头设置的主要内容,如果未能解决你的问题,请参考以下文章

使用eclipse构建springboot项目

Maven多模块构建实例

禁用 Maven 警告消息 - “选定的战争文件包括将被忽略的 WEB-INF/web.xml”

Maven 中的“需要 webxml 属性”错误

Maven学习遇到的坑

maven篇