CORS Issues (IONIC 3)

2019-08-09 01:30发布

问题:

I’m trying to handle with CORS issues in livereload mode, but I wasn’t able to find a reasonable solution for that. My backend was developed in Java and it’s running on localhost.

Command:

ionic cordova emulate ios -l -c -s --address 127.0.0.1

ion.config.json:

{
  "name": "Smartmarket",
  "app_id": "",
  "type": "ionic-angular",
  "integrations": {
    "cordova": {}
  },
  "proxies": [{
        "path": "/SmartmarketWeb/endpoint",
        "proxyUrl": "http://127.0.0.1:8080/SmartmarketWeb/endpoint"
  }]
}

Request example:

let headers = new Headers({ 
    'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
return this.http.post('http://127.0.0.1:8080/SmartmarketWeb/endpoint/login', json, options)
    .timeout(TIMEOUT_REQUEST*1000)
    .map(this.extractData)
    .do(this.logResponse)
    .catch(this.handleError);

Error:

Can anyone help me, please? I’ve tried to follow many solutions, however, none of them had an effect.

回答1:

The problem was on the server side. Follow the solution below (Java - Jersey 2):

Filter class:

@Provider
public class CORSResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");    
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");          
        headers.add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        headers.add("Access-Control-Allow-Credentials", "true");


    }

}

web.xml:

<servlet>
    <servlet-name>Endpoint</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.smartmarket.endpoint</param-value>
    </init-param>
    <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>com.smartmarket.filter.CORSResponseFilter</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


回答2:

Workaround only - Not a perfect solution


I was running with the same problem, My ionic 3 app with ASP.net backend was working just fine, it was not working with IOS ( Iphone x - IoS 11 simulator ).

Solution

I changed the web view option of my ionic app.

First, open config.xml and add the following properties

<feature name="CDVWKWebViewEngine"> <param name="ios-package" value="CDVWKWebViewEngine" /> </feature> <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />

Then remove all plugins and platforms then run or build your app

Detailed steps given in this url