使用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包。资源如下:点击打开链接

没有更多推荐了,返回首页