2016-09-27 91 views
1

我有一個Angular應用程序在端口上運行。而我的Rest服務器正在端口上運行。爲所有請求添加額外的頭文件(Angular to Tomcat)

我想爲所有向其他服務器發出的請求添加一個額外的頭文件。

所以,這裏是休息服務器的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

+2

我想,錯誤是在預檢請求(OPTIONS)上,是不是? 您是否需要將'x-rest-version'添加到'cors.allowed.headers'? – Ruben

+0

哇,太棒了!這很有趣,因爲我已經根據tomcat.apache.org/tomcat-7.0-doc/config/filter.html玩過這個參數,但從來沒有理解我必須將'x-rest-version'放在'param-value'節點中。現在正在工作。 – David

+0

高興地幫忙,我會發佈一個迴應,讓這個問題回答一些關於錯誤的更多細節。 – Ruben

回答

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> 
... 
相關問題