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

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://*/*" />

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.

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.

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

Related

I'm getting "blocked by CORS policy" when I try to call Instagram API using Axios [duplicate]

This question already has answers here:
Access-Control-Allow-Origin with instagram api
(1 answer)
CORS error, when i use instagram API with angularjs
(1 answer)
Closed 3 years ago.
I'm trying to fetch some images from my Instagram account in a Laravel application with Vue as front end. When I try to do it in a standalone Vue app, it works well, but when I do so with Laravel, I got a message saying "has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response."
I'm using Laravel 5.8 and the Vue and Axios that comes within in and I'm using Homestead as my localhost server.
I've tried a lot of tips that I found here and on Google but I had no success. Basically, I'm trying the very basic of Axios call
beforeMount() {
axios.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]').then(response => console.log(response))
}
I already created a Cors middleware on Laravel and tried a lot of headers settings on Axios.
I'm basically trying to retrieve a list of my Instagram posts and bypass that cors / x-csrf error.
Laravel automatically applies the X-CSRF-TOKEN header to all axios requests. This is so you can communicate with your application without having to pass the CSRF token every time for POST, PUT, DELETE, etc.
resources/js/bootstrap.js (default settings)
/**
* Next we will register the CSRF Token as a common header with Axios so that
* all outgoing HTTP requests automatically have it attached. This is just
* a simple convenience so we don't have to attach every token manually.
*/
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
You should be able to remove the offending header by doing something like this:
beforeMount() {
// create a new instance so we don't delete the csrf token for other requests
let instance = axios.create();
// delete the x-csrf-token header
delete instance.defaults.headers.common['X-CSRF-TOKEN'];
// use the new instance to make your get request
instance.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]')
.then(response => console.log(response))
}
Your AJAX request to the Instagram API endpoint has to be sent as a jsonp request which means the dataType of the request has to be jsonp.
This blob in axios repository contains an example of sending a request using jsonp which is mentioned below.
Install jsonp package, if you haven't already.
npm install jsonp --save
and then;
const jsonp = require('jsonp');
jsonp('http://www.example.com/foo', null, (err, data) => {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
Below is an example of sending a request using jQuery method with jsonp dataType to the Instagram API endpoint.
$.ajax({
url: "https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]",
type: "GET",
crossDomain: true,
dataType: "jsonp",
success: function(response){
console.log(response);
}
});

Cross-Origin Request Blocked - Request to API from react localhost

I'm trying the javascript framework react and I need to fetch a token from an api off this service: https://api.monetizze.com.br/2.1/apidoc/#api-Security-Token. For that, I need to send along with the request my X_CONSUMER_KEY. That's the way I'm trying to do with the axios library:
axios.request('https://api.monetizze.com.br/2.1/token', {
headers: {
'X-Requested-With' : 'XMLHttpRequest',
'X_CONSUMER_KEY': 'here is my key'
}
});
The response I'm getting on the browser console is as follows:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://api.monetizze.com.br/2.1/token.
(Reason: CORS preflight channel did not succeed).
Have you experienced that issue and have solved it? Sorry about my very poor English and thank you very much.
http.get({
host: 'api.monetizze.com.br',
path: '/2.1/token',
headers: {
X_CONSUMER_KEY: 'your_consumer_key',
}
}, (result) => {
console.log(req.headers);
res.send(result.statusCode)
});
That piece of code above in a server side application did the job, thank you very much.

Ext.Ajax Cross-Domain post request

I'm testing ExtJS v.5.1.0.107 and I my goal is that to perform a post ajax request on a different server. I've found some similar discussions but nothing seems to work for my scenario.
Here's request code:
Ext.Ajax.request({
url: 'http://192.168.1.60/test.php',
method: 'POST',
cors: true,
useDefaultXhrHeader : false,
params : {
myPar1 : myPar1Value
},
success: function () {
alert('success');
},
failure: function () {
alert('failure');
}
});
Here's error message:
XMLHttpRequest cannot load http://192.168.1.60/test.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.50:22800' is therefore not allowed access.
Is there something wrong?
Hope someone can help me.
Thanks to all.
Make sure your files are reachable from the server...
If the server is well configured, try add a response header for
Access-Control-Allow-Origin: *
This command will allow cross-domain through Ajax operations. Then, the requested file (test.php for instance on the targeted server) should contain in the first lines :
<?php header('Access-Control-Allow-Origin: *'); ?>
Then, you should change parameter for Apache server hosting test.php file. In the .htacess file :
header set Access-Control-Allow-Origin "http://192.168.1.60/"
Hope this helps !

Crossdomain post with easyXDM

I'm trying to get a crossdomain post to work. I know I can easily use jsonp for GET, but I'm stuck as to how I can implement POST requests.
I've looked up easyXDM, but as I understand it the server also needs some kind of easyXDM implementation, in the form of a "cors" file or something.
Is that true? So if the server does not support it, there's no way to do a crossdomain post (without setting up a proxy, that is)
I've tried it myself with only local files:
<script type="text/javascript">
var xhr = new easyXDM.Rpc(/** The channel configuration*/{
remote: "name.html"
}, {
remote: {
request: {} // request is exposed by /cors/
}
});
</script>
And then do a request like this:
xhr.request({
url: "http://other.domain.be",
method: "POST",
data: {NEWS: "true", IMMO: "true" }
}, function(response) {
alert(response.status);
alert(response.data);
});
But that does nothing.
Yes, easyXDM.Rpc need to be initialized using the server cors url.
xhr = new easyXDM.Rpc({remote: "http://url/cors"}, {remote:{request:{}}});
If you don't want to use easyXDM, you can easily set up the server to accept all requests by adding : (doesn't supported by IE<8)
Header set Access-Control-Allow-Origin *
Header add Access-Control-Allow-Headers X-Requested-With
Header add Access-Control-Allow-Headers X-Request

dojo ---> django POST

I'm trying to send a json from the client using the method xhrPost dojo. But I'm getting a 403 errors. Any help?
var str_json = dojo.toJson(arr_markers);
console.log('json elements: '+str_json);
dojo.xhrPost({postData: str_json,
headers: { "Content-Type": "application/json"},
//content:{'prueba': 'HOLA'},
url:'/up_position_elements/',
handleAs: 'text',
load: function(response, ioArgs){alert('response');},
error: function(errorMessage){}
});
And how to read the json in the django view?
Which method should I use?
403 means "forbidden" which means that the view wants a password, cookie, or other form of authentication. Could you show us the view that serves /up_position_elements/ so that we can see what security-related decorators or logic it might contain?

Resources