1

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://*/*" />
shah
  • 1,163
  • 2
  • 19
  • 40

3 Answers3

1

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.

Sohan
  • 1,121
  • 1
  • 14
  • 27
  • I have already installed the plugin for chrome. Also the `header('Access-Control-Allow-Origin: *');` is there in API. I don't know angular `http` is not working. But this plugin `cordova-plugin-advanced-http` is working perfectly. – shah Oct 11 '17 at 11:15
1

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.

Paul Isaris
  • 414
  • 4
  • 13
0

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")

Marouan
  • 217
  • 1
  • 8