Add to the body of the Axios POST - http

I am wondering how I can add this to the body of the Axios POST request.
const res = axios({
method: 'post',
url: 'https://fitness.googleapis.com/fitness/v1/users/me/dataset:aggregate',
headers: {
'Authorization': 'Bearer ACCESS_TOKEN'
}
});
I want to add this to the Body but I dont have a clue how to do it:
{
"aggregateBy": [{
"dataSourceId": "derived:com.google.calories.expended:com.google.android.gms:platform_calories_expended"
}],
"bucketByTime": { "durationMillis":86400000 },
"startTimeMillis" : 1617667200000,
"endTimeMillis" : 1617703858000
}

Heres how I got it to work:
const res = await axios({
method: 'post',
url: 'https://fitness.googleapis.com/fitness/v1/users/me/dataset:aggregate',
headers: {
'Authorization': 'Bearer ACCESS_TOKEN'
},
data: {
aggregateBy : [{
dataSourceId : "derived:com.google.calories.expended:com.google.android.gms:platform_calories_expended"
}],
bucketByTime : {durationMillis : 86400000},
startTimeMillis : 1617667200000,
endTimeMillis : 1617703858000
}
});

Related

Recognize Text REST endpoint returns no results on success

I'm using the recognizeText REST endpoint from javascript running locally on my dev machine. I can successfully call the endpoint, get the operation-location url for the result and send a GET request to that url.
The issue is the return from the operation-location url is 200 success (meaning the operation has completed and doesn't need more time), but the body of the result is always empty.
How can I get the extracted text from the response?
My code:
var subscriptionKey: string = "my key";
var endpoint: string = "https://eastus.api.cognitive.microsoft.com/";
var uriBase: string = endpoint + "/vision/v2.0/recognizeText?mode=Printed";
const fetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
body:
'{"url": "https://www.bing.com/th/id/OIP.nZoyhANat4WNndv0jeoXFAHaLp?w=183&h=289&c=7&o=5&dpr=1.5&pid=1.7"}',
method: "POST"
};
fetch(uriBase, fetchData).then(data => {
var operationLocation = data.headers.get("Operation-Location");
if (operationLocation) {
const resultFetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
method: "GET"
};
setTimeout(function(operationLocation, resultFetchData) {
fetch(operationLocation, resultFetchData).then(resultData => {
alert(JSON.stringify(resultData, null, 2));
});
}, 10000);
}
});
}
There is something wrong with your fetch request code block, try this :
fetch(uriBase, fetchData).then(data => {
var operationLocation = data.headers.get("Operation-Location");
if (operationLocation) {
const resultFetchData = {
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},
method: "GET"
};
setTimeout(()=> {
fetch(operationLocation, resultFetchData).then(resultData => {
return resultData.json();
}).then((data)=>{
console.log(JSON.stringify(data, null, 2));
});
},10000);}
});
Result :

How to pass params with body in flutter http put method

Hi i am trying to pass the query prams to http put method.
Here i am trying in this way
var queryParameters = {
'id': '285',
};
return http.put(
'http://domainname${queryParameters}', body: json.encode(formData)
,
headers: {
'Authorization': receivedToken,
'X-Oc-Store-Id': receivedstoreid,
},
try this,
var body = jsonEncode({
"email": "${emailController.text}",
"password": "${passwordController.text}"
});
.
var response = await http.put("http://domainname + /${id}", body: body, headers: {
'Authorization': receivedToken,
'X-Oc-Store-Id': receivedstoreid,
}).timeout(Duration(seconds: 30));

Ionic 2 http.post to login

I'm trying to convert an ionic app in an ionic 2 app and im strugle trying to remake the login progress.
I wrote this in my ionic 2 app:
loginUser(){
localStorage.setItem('username', this.username);
localStorage.setItem('password', this.password);
localStorage.setItem('company', this.company);
this.loginData = {};
this.loginData.UserID = this.username;
this.loginData.CompanyID = this.company;
this.loginData.Password = this.password;
let body = {"jsonLogin": JSON.stringify(this.loginData)}
let link = 'working link';
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
});
let options = new RequestOptions({headers: headers});
this.http
.post(link, body, options)
.map(res => res.json())
.subscribe(
data => {
console.log(data);
//this.navCtrl.push(MenuPage);
}, err => {
console.log(err);
});
}
While in the ionic 1 app this was the code:
$scope.loginUser = function () {
json = {};
json.UserID = $scope.data.username;
json.CompanyID = $scope.data.company;
json.Password = $scope.data.password;
$http({
method: 'POST',
data: {
"jsonLogin": JSON.stringify(json)
},
url: 'working link',
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
}
My problem is in the POST, when I post with my code of the ionic 2 app this is what my Form Data looks like:
{
"jsonLogin": "{\"UserID\":\"admin\",\"CompanyID\":\"test\",\"Password\":\"pass\"}"
}:
While the ionic 1 app Form Data looks like this:
jsonLogin:{"UserID":"admin","CompanyID":"test","Password":"pass"}
The POST is working since I got an error message from server, I just don't know how I can format the data to do a correct POST.
Thank you in advance for the help.
EDIT:
Got it working by added a new header:
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'
});
And send a hardcoded string:
createStringForLogin(username: any, company: any, password: any){
return 'jsonLogin={"UserID":"'+username+'","CompanyID":"'+company+'","Password":"'+password+'"}';
}
I think
let body = {"jsonLogin": this.loginData};
should solve your problem. Let me know if it does not work.
Also, if you are having trouble in setting parameters to this.loginData. Set them like this:
this.loginData = {};
this.loginData['UserID'] = this.username;
this.loginData['CompanyID'] = this.company;
this.loginData['Password'] = this.password;

Microsoft Graph with OneDrive API, invite : fail with Unsupported segment type

Using jquery, I've managed so far to send a Copy Item request( POST /me/drive/items//copy),
however if I try to add permission ( POST /drive/items//invite), I receive the "Unsupported segment type" error.
The API documentation :
graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_invite
(I copied the two function to compare)
// working:
copyFile:function(id, folderId){
// https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_copy
// POST /me/drive/items/<id>/copy
var endpointUrl = 'https://graph.microsoft.com/v1.0/me/drive/items/'+id+'/copy';
var data={};
data.parentReference={'id':folderId}
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
processDate: false,
datatype : "json",
method: "POST",
//http://stackoverflow.com/questions/13956462/jquery-post-sends-form-data-and-not-json
data: JSON.stringify(data),
url: endpointUrl,
contentType : 'application/json',
headers : { "authorization" : "Bearer " + token }
}).success(function(data) {
alert('success!')
});
},
///NO WORKING ?
invite:function(id, user){
// http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_invite
// POST /drive/items/<id>/invite
var endpointUrl = 'https://graph.microsoft.com/v1.0/drive/items/'+id+'/invite';
data={
"requireSignIn": true,
"sendInvitation": false,
"roles": "read",
"recipients": [ { "email": user }],
"message": "NO MESSAGE ?"
}
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
datatype : "json",
method: "POST",
data: JSON.stringify(data),
url: endpointUrl,
contentType : 'application/json',
headers : {"authorization" : "Bearer " + token}
}).success(function(data) {
alert( 'success!')
});
API return:
{
"error": {
"code": "BadRequest",
"message": "Unsupported segment type. ODataQuery: drive/items/***********/invite",
"innerError": {
"request-id": "********",
"date": "2016-09-14T09:01:32"
}
}
}
Did I miss something ?
It seems the v1.0 version does not currently works. I swapped to beta, using this url:
var endpointUrl = 'https://graph.microsoft.com/beta/me/drive/items/'+id+'/invite';
And it works

using $http with AngularJS

I have the following
angular.module('myApp').factory('dashboard', ['$http', function ($http) {
return {
name: function(str){
return str + ':' + 'works!';
},
getFlags : function(){
$http({ method: 'GET', url: 'http://dalsapent01:8080/DataService/TestDataService.svc/EventTypes', headers: { 'Content-Type': 'application/json; charset=utf-8', 'dataType': 'json' } })
.success(function (data, status, headers, config) {
alert(data);
}).
error(function (data, status, headers, config) {
alert(data);
});
}
}
}])
when I look in fiddler, I see JSON being returned, but status is always 0. any Idea?
Thanks
I think you have a problem in your server response configuration.
Trying your code in this plunker, everything works fine.

Resources