为所有请求添加额外的标头(Angular to Tomcat)

时间:2016-09-27 10:11:23

标签: angularjs tomcat http-headers

我在端口 3000 上运行 Angular app 。我的休息服务器正在端口 8080 上运行。

我想为所有向其余服务器发出的请求添加一个额外的标头。

所以,这是其余服务器的web.xml配置文件:

<filter>

    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>

    <!-- With or without this, it doesn't work -->
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    </init-param>

    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>http://localhost:3000</param-value>
    </init-param>

    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
    </init-param>

    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Location</param-value>
    </init-param>

</filter>

当我在interceptor.js中添加它时:

config.headers["x-rest-version"] = "2.0.0"; // version dynamically generated

服务器返回403:

# 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:3000' is therefore not allowed access. The response had HTTP status code 403.

enter image description here

enter image description here

当我删除javascript文件中的行时,请求已成功完成。

enter image description here

1 个答案:

答案 0 :(得分:1)

HTTP服务器用于检查HTTP标头,并且您尝试传递标头x-rest-version并且它未在配置中列入白名单。

x-rest-version添加到cors.allowed.headers

...
<init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>x-rest-version,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
...
相关问题