使用cors解决跨域,ionic打包到android手机上发post请求报403错误

如题,百度了一圈也没有找到答案,最后翻了个墙,最终找到了外国友人的答案:
https://forum.ionicframework.com/t/ionic-http-request-with-403-error-on-ipad-device/50269/2
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如下。
CorsFilter
com.thetransactioncompany.cors.CORSFilter
cors.allowOrigin
*
cors.supportedMethods
GET, POST, HEAD, PUT, DELETE
cors.supportedHeaders
Accept, Origin, X-Requested-With, Content-Type, Last-Modified
cors.exposedHeaders
Set-Cookie
cors.supportsCredentials
true
CorsFilter
/*

当然需要引入两个jar包。资源如下:点击打开链接

你可能感兴趣的:(ionic1)