I'm using phonegap to develop an inventory management mobile application and I can't figure out how to send http request without running into the CORS policy problem. I installed the cordova advanced http plugin but when I preview the app on chrome, the cordova object doesn't exist because the cordova.js script isn't added until later so I haven't really been able to tinker with the plugin. I simply want to send an http request and read back a JSON. I have a URL. There is no username or password. Please help! I'm stuck!
Update:
I used this code:
$.ajax({
url: 'https://api.barcodelookup.com/v2/products?barcode=075500000010&formatted=y&key=8f5uvzskkmjnptt43bz7yjzgwehscl',
data: null,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
});
And the request went through, now, but the response is being blocked. I tried whitelisting by putting this in my xml:
allow-intent href="https://api.barcodelookup.com/*"
access origin="https://api.barcodelookup.com/*"
But I still get this error saying that the response was blocked:
jquery-1.11.1.min.js:4 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api.barcodelookup.com/v2/products?barcode=075500000010&formatted=y&key=8f5uvzskkmjnptt43bz7yjzgwehscl&callback=jQuery111107483149196833481_1568855081600&_=1568855081601 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Well, you could simply add jQuery to your app and do
$.ajax({
url: "http://localhost/",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status) {
alert("error");
}
});
You could also try this depending on your backend (and post your data as a JSON string)
$.ajax({
method:'POST',
url:url,
data:json_string,
async:true,
processData:false,
contentType:'application/x-www-form-urlencoded',
dataType:'json',
...
);
u can use this in your API php
header('Access-Control-Allow-Origin: *'); header("Content-Type: application/json; charset=UTF-8");
Okay. I finally got it: I had to use the cordova advanced http plugin. I used the following code:
const options = {
method: 'get',
headers: { Authorization: 'OAuth2: token' }
};
cordova.plugin.http.sendRequest('https://api.upcitemdb.com/prod/trial/lookup?upc=075500000010', options, function(response) {
// prints 200
alert(response.status);
var obj = JSON.parse(response.data); // This is the resultant JSON in useful form
}, function(response) {
// prints 403
alert(response.status);
//prints Permission denied
alert(response.error);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.