1. 程式人生 > >使用cors解決跨域,ionic打包到android手機上發post請求報403錯誤

使用cors解決跨域,ionic打包到android手機上發post請求報403錯誤

如題,百度了一圈也沒有找到答案,最後翻了個牆,最終找到了外國友人的答案: My backend is using Tomcat, one of the tomcat filters is designed for handle CORS request, it named: org.apache.catalina.filters.CorsFilter, it has a design flaw in handling the "Origin" send from ionic, the $http sends "file:///" as the value of header "Origin", however, CorsFilter can not recognize the "file:///", it is expecting an URL start with "http://" or "https://", so marked the request from ionic app as an invalid request, then response with 403.
I have to re-write the CrosFilter in Tomcat to handle Origin header from ionic.。 總體解釋就是:我的後端採用了org.apache.catalina.filters.CorsFilter解決了跨域問題。但是它有一個問題,就是它只認origin以“http://”或“https://開頭的請求。而程式打包到android之後,它的origin的值將變成file://。所以此時伺服器就會拒絕掉請求。報403錯誤。解決方法為重寫CrosFilter 。 我的解決方法:採用com.thetransactioncompany.cors.CORSFilter替換掉org.apache.catalina.filters.CorsFilter,web.xml如下。
<filter> <filter-name>CorsFilter</filter-name> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> <init-param> <param-name>cors.allowOrigin</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.supportedMethods</param-name> <param-value>GET, POST, HEAD, PUT, DELETE</param-value> </init-param> <init-param> <param-name>cors.supportedHeaders</param-name> <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value> </init-param> <init-param> <param-name>cors.exposedHeaders</param-name> <param-value>Set-Cookie</param-value> </init-param> <init-param> <param-name>cors.supportsCredentials</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 當然需要引入兩個jar包。資源如下:
點選開啟連結