shah
shah

Reputation: 1169

Ionic 3 http post request invalid HTTP status code 403 while jQuery ajax post is working perfectly

I am working on a mobile app. I need to fetch some data from WordPress website but the http request always through error Response for preflight has invalid HTTP status code 403

Typescript

this._http.post('http://www.example.com/wp-admin/admin-ajax.php',{
      'action' : 'get_votes',
      'postId' : 123456
    })
    .subscribe(data=>{
      console.log(data);
    },error=>{
     console.log(error);
    })

jQuery

The same thing is working in jQuery on local server

$.ajax({
                url: 'http://www.example.com/wp-admin/admin-ajax.php',
                type: 'post',
                dataType: 'JSON',
                data: {
                    'action': 'get_votes',
                    'postId': 123456
                },
                success: function(result) {
                    console.log(result);
                },
                error: function(error) {
                    console.log(error);
                }
            });

The cordova-plugin-whitelist is already installed.

config.xml

<access origin="*" />
   <allow-intent href="http://*/*" />
   <allow-intent href="https://*/*" />

Upvotes: 1

Views: 1179

Answers (3)

Paul Isaris
Paul Isaris

Reputation: 483

This is a CORS (cross-domain) issue. Your browser (not Angular) is sending an OPTIONS request before sending the actual POST request. Effectively, your server discards the OPTIONS request as not authenticated (or forbidden in your case). Please read this answer for more info.

Have you tried to set a 'content-type' header as 'application/x-www-form-urlencoded' or 'multipart/form-data'? I think is would result in the browser not to send an OPTIONS request before sending the POST request. So, even if you solve the first problem (with the lack of OAuth header), you may still not be able to POST, because of the second problem.

You can also try and install the Chrome Allow-Control-Origin extension.

Upvotes: 1

Marouan
Marouan

Reputation: 217

you can use ionic proxy to work arround the CORS problem,

ionic.config.json

"proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://www.example.com/wp-admin/admin-ajax.php"
    }
  ]

and you call it this.http.post("/api")

Upvotes: 0

Sohan
Sohan

Reputation: 1131

If you are testing with web browser, there you need to allow origin access for web browser. with chrome use plugin and configure it https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

If you are using with real device and it is still not working try to use header('Access-Control-Allow-Origin: *'); with your server side API file.

More Info here.

Upvotes: 1

Related Questions