Cordova http plugin can't use POST method - http

I'm trying to use the cordova-plugin-http to update data on a spreadsheet using some apis and sheetdb.io. The problem is that I have this piece of code and I don't understand why when I run it on my phone it doesn't work. When I try to use the POST method on a normal html page and it works.
const options = {
method: 'post',
data: { strada: 1,
orario_in: 23,
ora: 10,
minuti: 50,
orario_fin: 23,
tempo: 120},
headers: { Authorization: 'OAuth2: token' }
};
alert("aa");
cordova.plugin.http.sendRequest('MY_TOKEN', options, function(response) {
alert(response.status);
}, function(response) {
alert(response.status);
alert(response.error);
});
alert("bbb")
I followed the guide of the plugin exatly but it seems to not even enter the function

Related

Weird 401 and 403 with wordpress REST API (wp-json)

I am getting mad because as a lodded-in wordpress admin, on the front-end (not in the admin portal), I cannot make post/put requests.
A simple GET AJAX request works perfectly without any type of credentials:
axios.get(this.page.url + "/wp-json/wp/v2/posts").then((resp) => {
console.log(resp.data);
});
BUT, when I try to make post requests I always get 401 error if I do not include the nonce.
If I include the nonce, I get 403. Tried with both AXIOS and JQUERY:
// Axios:
axios.defaults.withCredentials = true;
axios.defaults.headers.post["X-WP-Nonce"] = MYSCRIPT.nonce; // for POST request
axios
.post(this.page.url + "/wp-json/wp/v2/posts", {
title: "title",
content: "content",
status: "publish",
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// JQUERY
$.ajax({
url: this.page.url + "/wp-json/wp/v2/posts",
type: "post",
data: {
title: "title",
content: "content",
status: "publish",
},
headers: {
"X-WP-Nonce": MYSCRIPT.nonce, //If your header name has spaces or any other char not appropriate
},
dataType: "json",
success: function (data) {
console.info(data);
},
});
The nonce is simply generated with:
<script>
<?php echo 'const MYSCRIPT = ' . json_encode(
array('nonce' => wp_create_nonce('wp-rest'))
); ?>
</script>
I know this is not good practice, and I will include it properly as soon as I get it to work.
The nonce is perfectly retrieved by Javascript, but I get 403 from wordpress...
No idea on how to proceed!
The action specified in wp_create_nonce should be wp_rest (underscore), not wp-rest (hyphen).
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest
Replace wp-rest with wp_rest and it should work properly.

GET operation status via API not CMD

In Google Cloud vision API documentation for the product search, the method for getting operation status is listed as CMD but there is no C# code example for it in order to check any long-running operation status.
I tried calling this method in postman but it didn't work as I cannot add the service account credentials
GET https://vision.googleapis.com/v1/locations/location-id/operations/operation-id
Would appreciate any guidance on this.
It turns out there are two solutions:
Using Google Cloud Vision REST APIKEY as a query parameter for (you will have to generate your own API key from the cloud console credentials)
GET https://vision.googleapis.com/v1/locations/location_id/operations/operation_id?key=value
Using AJAX with stringify to append the service account JSON key file with the request which is sent to the same URL above.
checkStatus: function() {
if (this.get('stop') || !this.getOperationUrl()) {
return;
}
$.ajax({
url: '/getOperation',
type: 'POST',
data: JSON.stringify({
operation_url: this.getOperationUrl(),
key: this.config_model.get('key'),
}),
cache: false,
contentType: 'application/json',
dataType: 'json',
}).done(function(response) {
const result = response.response;
if (!response.success || !result) {
console.log(response);
this.set('response', response);
} else {
if (result.done) {
this.set('response', response);
} else {
setTimeout(function() {
this.checkStatus();
}.bind(this), 5 * 1000);
}
}
}.bind(this));

WooCommerce Add to cart products via co-cart plugin

I am new to WooCommerce REST API. I want to add product to cart and list all products of cart. I have added Co-Cart plugin to my server and I am using Co-Cart APIs for cart related functionality.
Issue I am facing is, I am not able to view cart products in my react native application. Here are the APIs I am using right now:
1. Add product to cart:
Method:POST
URL: https://www.myhost.com/wp-json/wc/v2/cart/add?token=user_token
Parameteres: {
"product_id": "9168",
"quantity": "1"
}
Response:{
"key": "af086cdab7954f11a518e3af68XXXXX",
"product_id": 111,
"variation_id": 0,
"variation": [],
"quantity": 1,
"data": {},
"data_hash": "b5c1d5ca8bae6d4896cf1807cdfXXXX",
"line_tax_data": {
"subtotal": [],
"total": []
},
"line_subtotal": 50000,
"line_subtotal_tax": 0,
"line_total": 50000,
"line_tax": 0
}
Getting proper response with status code 200 while adding product to cart from application.
2. View cart content
Method: GET
URL: https://www.myhost.com/wp-json/wc/v2/cart?token=user_token
Response: [] (Blank JSON array)
I don't know where are the products which are added to cart using same user. I don't how it manages session from mobile application or what extra parameters it requires to fetch cart items.
Please let me know where I am going wrong. I am using Co-Cart plugin API only.
**
EDIT
**
fetch(url, {
method: methodName,
async: true,
crossDomain: true,
headers: new Headers({
"Content-Type": "application/json",
"cache-control": "no-cache",
}),
body:data
}).then((response) => {
const statusCode = response.status;
console.log("fetchData StatusCode : "+statusCode);
console.log("fetchData response1 : " + JSON.stringify(response));
console.log("fetchData response2 : " + response);
return response.json();
}).then((responseJson) => {
console.log("fetchData responseJson : "+responseJson);
var response = JSON.stringify(responseJson);
console.log("fetchData responseJson stringify : " + response);
response = JSON.parse(response);
if (callBack != null) {
callBack("", response);
}
}).catch((error) => {
console.log("fetchData Api error : "+error);
if (callBack != null) {
console.log("fetchData Api error callBack != null 2");
callBack("Error", "");
}
});
url is a URL to send, data is raw data in JSON string format and method is either GET or POST.
Here is the answer of my own question.
It is somehow difficult to integrate WooCommerce store into Mobile Application without having prior knowledge of WooCommerce and its working criteria.
The issue was it was not adding products to my logged-in user's cart and that's why it was not getting all the products for that user as products were not added to the user's cart.
The issue why it was not syncing my cart with my current user was for cookie session for that particular user. I need to set cookie of that user in each API call header after login something like this:
fetch(url1, {
method: methodName,
async: true,
crossDomain: true,
headers: new Headers({
"Content-Type": "application/json",
"cache-control": "no-cache",
"cookie":"cookie value will goes here"
}),
body:data1
})
It just resolved my issue. Hope it helps!
I check the documentation, https://co-cart.github.io/co-cart-docs/#view-cart-contents and but nothing wrong with your.
Can you check if the Pretty permalinks in Settings > Permalinks so that the custom endpoints are supported. Default permalinks will not work.

Send multiple parameters when axios upload image

I'm uploading images with formdata and axios. I'm using symfony for my back end and I need to access my image file and other parameter both. This is my axios code.
axios.post(testUp, { data: formData, ad: 12 }, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
});
And here is my symfony code.
/**
* #Route("/test_up", name="test_up", methods={"GET","POST"})
*/
public function testUp(Request $request, CarRepository $carRepository) {
dd($request->files->all());
}
Unfortunately I'm getting null as output. I'm getting the formdata from image uploaded and it's a formdata object. It works if I do this but need both parameters.
axios.post(testUp, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
alert('*');
console.log(response);
});
but I need to send other parameter too.
You cant mix FormData with JSON. It is related question
Send FormData object AND an additional parameter via ajax
If you have only one parameter - ad = 12 I recommend to use code:
axios.post(testUp + "?" + (new URLSearchParams({ad: 12})).toString()
, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
alert('*');
console.log(response);
});
On Symfony side you should use a form so you can receive many type of data. See documentation here: https://symfony.com/doc/current/forms.html
On vuejs/axios side, you just cant send json content AND form data content at the same time (as it is 2 different type of data). But you can add some content to your form data (just like you can have a file with other fields in your Symfony form).

Meteor JS HTTP get profile pic with Facebook API v2.5 - server side

I've tried with these Meteor HTTP.get methods in the server side:
HTTP.get(`http://graph.facebook.com/${fbUserId}/picture?callback=?`, {
headers: {
'content-type': 'application/json',
}
}, function(data){
console.log(data); // [Error: failed [400]]
});
HTTP.get(`https://graph.facebook.com/${fbUserId}/picture`, {
headers: {
'content-type': 'application/json',
}
}, function(data){
console.log(data); // null
});
However, this works in the client side with jQuery:
$.getJSON(`http://graph.facebook.com/${fbUserId}/picture?callback=?`, function(data){
console.log(data); // {url: 'http://img-url...'}
});
Any ideas?
UPDATE
#Ethaan answer worked (with a few additions):
function _fetchUserFacebookThumbnail(fbId){
return new Promise(function(resolve, reject){
HTTP.get(`https://graph.facebook.com/${fbId}/picture/?redirect=0&type=square`, function(error, data){
resolve(data['data']);
});
});
}
According to FB Developers docs, the ?redirect=0 query requests a JSON object instead of the image itself.
You are getting null on the second one because there is not error, so that means the second example work, try with error, data instead of just error.
Also if you only want to get the picuture you can just link to this.
facebookPicture = "https://graph.facebook.com/" + userFacebookId + "/picture/?type=large";
btw, mexican developer over here head ups =p.

Resources