Outlook Rest calling form angularjs - angularjs

Using outlook I am trying to create event, When i send request using POSTMAN its working fine, But same code in Angularjs its not wotking.
what is wrong with code.
Please help.
$scope.createEvents = function(){
var url = "https://outlook.office.com/api/v2.0/$metadata#Me/Calendars";
//var url = "https://outlook.office.com/api/v2.0/$metadata#me/Calendars";
var add_events = {
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2016-10-10T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2016-10-10T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "sathish.gopikrishnan#stradegi.com",
"Name": "Sathish Gopi"
},
"Type": "Required"
}
]
};
$http({
method: 'POST',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).Succes(function (response) {
alert("Saved")
});
I am getting.
Failed to load resource: the server responded with a status of 406 (Not Acceptable). To solve this problem i am using this code now
$scope.createEvents = function(){
var url = "https://outlook.office.com/api/v2.0/$metadata#Me/Calendars";
//var url = "https://outlook.office.com/api/v2.0/$metadata#me/Calendars";
var add_events = {
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2016-10-10T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2016-10-10T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "sathish.gopikrishnan#stradegi.com",
"Name": "Sathish Gopi"
},
"Type": "Required"
}
]
};
$http({
method: 'JSONP',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).Succes(function (response) {
alert("Saved")
});
After Using Jsonp as method I am getting this error
Uncaught SyntaxError: Unexpected token <

406 Not Acceptable is defined as the following:
The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.
see restapitutorial: http status codes
You send the following Accept header:
'Accept': 'application/json;odata.metadata=minimal'
The server says, it cannot produce this content type. If you got it running using postman, have a look at which accept header you've provided there.
Concerning your second try: jsonp is not an http method/verb (GET, PUT, POST, DELETE, PATCH). I'm not an angularjs expert but in case you need jsonp, there is a method you can call.
JSONP is a quite specific (and somewhat problematic) technique. So as long as you can do that, try to avoid it.

i know its an old post, i've had the same problem and this is the solution if someone falls into the same problem,
you should use https://graph.microsoft.com/v1.0/me/calendar/events as URL
Exemple tested code :
var url = "https://graph.microsoft.com/v1.0/me/calendar/events";
var add_events = {
"Subject": "Title",
"Body": {
"ContentType": "HTML",
"Content": " Exemple"
},
"Start": {
"DateTime": "2010-05-17T18:00:00",
"TimeZone": "UTC"
},
"End": {
"DateTime": "2010-05-17T19:00:00",
"TimeZone": "UTC"
}
};
$http({
method: 'POST',
url: url,
headers:{
'Authorization':'Bearer '+localStorage.getItem('Your Token here'),
'Content-Type':'application/json',
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*',
'token_type':'Bearer'
},
data: add_events
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
localStorage.setItem('etat_mytoken', 0);
$window.location.href = url_base+'/'+url_base_v+'/app/assets/views/token.html';
});

Related

Can't read response data and headers in an AngularJS interceptor

I have an API in my server that sends a custom header (lets name it "customHeader") that responds to http://localhost:8081/my/test/api.
I'm trying to read that custom response header from an interceptor in angularJS:
angular.module('oauth.interceptor', []).factory('readResponseHeader', ['$q',
function ($q) {
return {
response': function(response) {
console.log("response: %o", JSON.stringify(response));
console.log("headers: %o", response.headers());
return response;
}
}
}
]);
But all I get are empty data and headers in response. The console log shows the following json as response:
{
"data": [],
"status": 200,
"config": {
"method": "POST",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:8081/my/test/api",
"data": {
"example": "request data"
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Bearer XXXXXXXXX..."
},
"cached": false
},
"statusText": "OK"
}
And the following as headers:
{
"content-type": "application/json; charset=UTF-8"
}
I expected my customHeader to be there, and be able to read it with something like:
response.headers().customHeader
But it clearly isn't there (in fact, many other headers are missing!).
How am I supposed to read it?
I finally found the problem wasn't really in the AngularJS part, but on the server side part.
The point is that, to be able to access the header, the server must add the Access-Control-Expose-Headers header containing the name of the custom header, something like this:
Access-Control-Expose-Headers: customHeader

firestore is rejecting post request from angularjs

i'm trying to add a new document to the collection Offers by using $http.post method in angularjs.
i'm getting this error in the console:
Possibly unhandled rejection: {
"data": {
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\nfields%5BcompanyName\n^",
"status": "INVALID_ARGUMENT"
}
},
"status": 400,
"config": {
"method": "POST",
"transformRequest": [null],
"transformResponse": [null],
"jsonpCallbackParam": "callback",
"url": "https://firestore.googleapis.com/v1beta1/projects/syrian-sales-v2/databases/(default)/documents/Offers",
"data": "fields%5BcompanyName%5D=qwe&fields%5Bdescription%5D=qwe&fields%5BexpiredDate%5D=qwe&fields%5Btitle%5D=qwe&fields%5BuserId%5D=rsVWKar7UTMwUmcyYJbr6Rif4NN2",
"headers": {
"Content-Type": "application/json; charset=UTF-8;",
"Accept": "application/json, text/plain, /"
}
},
"statusText": "",
"xhrStatus": "complete"
}
i have tried so many solutions but none worked.
here's the controller code:
app.controller('insert_controller', function ($scope, $http, $httpParamSerializerJQLike) {
let userId = "rsVWKar7UTMwUmcyYJbr6Rif4NN2";
let url = "https://firestore.googleapis.com/v1beta1/projects/syrian-sales-v2/databases/(default)/documents/Offers";
$scope.insertOffer = function () {
let companyName = $scope.companyName;
let title = $scope.title;
let expiredDate = $scope.expiredDate;
let description = $scope.description;
let data = {
"fields": {
"companyName": companyName,
"title": title,
"expiredDate": expiredDate,
"description": description,
"userId": userId,
}
};
$http({
method: 'POST',
url: url,
data: $httpParamSerializerJQLike(data),
headers: {
'Content-Type': 'application/json; charset=UTF-8;'
}
}).then(function (res) {
if (res.data){
$scope.companyName = null;
$scope.title = null;
$scope.expiredDate = null;
$scope.description = null;
alert('Offer Added Successfully')
}
}).catch(function (err) {
console.log(err);
throw err
});
}
});
any help would be great, thanks in advance
EDIT: i tried sending a post request from postman and it worked to the same url and the same json data structure i'm using
the problem was that I was using a wrong schema.
This is the old schema:
let data = {
"fields": {
"companyName": companyName,
"title": title,
"expiredDate": expiredDate,
"description": description,
"userId": userId,
}
};
This is the correct schema which worked:
let data = {
"fields": {
"companyName": {
"stringValue": companyName
},
"title": {
"stringValue": title
},
"expiredDate": {
"stringValue": expiredDate
},
"description": {
"stringValue": description
},
"userId": {
"stringValue": userId
},
}
};

How to display image returned from fetch() method - react-native

I have the following code to retrieve an image from an API
await fetch('https://example.com/api/user/fileaccess', {
method: 'POST',
headers: {
Accept: '*',
'Content-Type': 'application/json',
'token':'xxxxxxxxxxxxxxxxxxxxxxxx'
},
body: JSON.stringify({"applicantid": xxxx, "user_secret": "xxxxxxxxxxx","fileid":xxxxx}),
}).then((response) => {
console.log(response);
});
The request was completed and i got log in my console.
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId":
"xxxxx-xxxx-xxx-xxxx-xxxxx", "offset": 0, "size": 953328}},
"_bodyInit": {"_data": {"__collector": [Object], "blobId":
"xxxxx-xxxx-xxxx-xxxx-xxxxx", "offset": 0, "size": 953328}},
"headers": {"map": {"cache-control": "max-age=2592000", "connection":
"Keep-Alive", "content-type": "image/jpeg", "date": "Tue, 04 Feb 2020
10:34:14 GMT", "expires": "Thu, 05 Mar 2020 10:34:14 GMT",
"keep-alive": "timeout=5, max=100", "pragma": "public", "server":
"Apache", "transfer-encoding": "chunked"}}, "ok": true, "status": 200,
"statusText": undefined, "type": "default", "url":
"https://example.com/api/user/fileaccess"}
My question is, How to display this data as an image in my app? Is it possible to convert a base64 from this data?
You need to extract it into json or text or some other data before you can do anything with the response.
As per Mozilla docs, A basic fetch request is really simple to set up. Have a look at the following code:
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
So, modify your code as below :
fetch('https://example.com/api/user/fileaccess', {
method: 'POST',
headers: {
Accept: '*',
'Content-Type': 'application/json',
'token':'xxxxxxxxxxxxxxxxxxxxxxxx'
},
body: JSON.stringify({"applicantid": xxxx, "user_secret": "xxxxxxxxxxx","fileid":xxxxx}),
})
.then(response => response.json())
.then((result) => {
console.log("Your intended result is: " , result)
});
The response.json() is added just assuming the server is returning a JSON data.
If not, you can try the below methods too based on your server implementation.
arrayBuffer()
blob()
json()
text()
formData()
If that's the image URL you can go ahead as follows
Store image in your state
this.setState({image:res.url})
and then <Image source={{uri:this.state.image}}/>

I want to send the meeting invite using angularjs. But facing some issues

I am using the rest api of outlook for sending the request. But when i am calling this with above code, in console i am getting error
unhandled exception
$scope.createEvents = function(){
alert("here");
var url = "https://outlook.office.com/api/v2.0/$metadata#Me/Calendars";
$scope.token = "AQABAAIAAADX8GCi6Js6SK82TsD2Pb7rFu9WBTIi5a6r4Up0vk8NCmPR719K3Uiz7NPUBoT9RwewzSWjPfUIybYn9fVVF2dhQ8b0ObN3oIv5Tq91GwZiTuyBhWZ_s07uDJpCUh40K4Bn2F5eEP9TAp8-5eMY0hfyXb4vIukQwTAe9yXCG75WUS08M7m-_kFbtx-TVq-Y2-SKh8Ut7-v4UQq4NYhlf5LQC1arNbwAZVndfND1vSNGcs1BVJboWd7bcgohHecaR57cAuFav2vfsVEm8n3_IKnlapHzWsyXOw7gXnxTmH2pkfAie0LCiQv8C8nQRnYnLquaWKg6b_ZzTl4ela0EwC9cN74BVMQHFWm6NY1EVM8s-HYevrT8R-WwkAUJXprP40Jp-weLY4-K7vOGk0N0n6fQIeu_WoORIZ18-oKxda6j4XunmrLbWEapQy-Oms9BIAs-AZIVN6Ph1zxQk3CC1bbGK6QkiiL4c2Sgrx_6YoxZt1cMh36pjhbe_TxpC2alk5zJineTK0AZUdGJQWGoy-9fTwtzTbYiaRaV4rispV-q-yiYzpWQ1UWROIPZ5qDq2jlCV7ovTDCWhNd_JgKzzHf-2wANBun9WcX924UVcLkkfvh6XU-QxCo1N6gfGYGUwNNJA1kTZjSyxgKSOAKGxKXz96r5qbtJp34Ci9lEO-PpSeLAL5gHoUOX_PlbM_FO4mLcNEu_fB0Us-5sbV8pKPU-WnfLq3PI8gK3lCi5D_itjesuex1f-o1d1vJ3M4jvx-sgAA";
var add_events = {
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2016-10-10T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2016-10-10T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "nishanth.singh#subex.com",
"Name": "Nishanth Kumar Singh"
},
"Type": "Required"
}
]
};
$http({
method: 'JSOPN',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).Succes(function (response) {
alert("Saved")
});
}
Replace
}).Succes(function (response) {
with
}).success(function (response) {
You have used upper case Success in your code & the spelling is incorrect as well. Let me know once you made this change.
Try to use .then() rather than success() as success() has been deprecated.
Update 1
Since you are using version 1.6, use .then(). success() is deprecated as I said
$http({
method: 'JSOPN',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).then(function (response) {
alert("Saved")
});
Update 2
You are now facing CORS issue. for quick fix try chrome plugin.
Get proper header to complete the request or you need to config the server to handle such requests.
change method: 'JSOPN' to
method: 'JSON'

Login with $cordovaOauth in Facebook returns null data

I am using $cordovaOauth to authenticate on an Ionic app (angular/cordova) but after settings everything on developers.facebook.com and getting the access_token I call again to get user data, but it returns an error with data=null.
Code:
$scope.facebookLogin = function() {
$cordovaOauth.facebook(FACEBOOK_ID, ["email", "public_profile"], {
redirect_uri: "http://localhost/callback"
}).then(function(result) {
var access_token = result.access_token;
//console.log(JSON.stringify(result));
$http.get("https://graph.facebook.com/v2.2/me", {
params: {
access_token: access_token,
fields: "first_name,last_name,gender,picture,locale",
format: "json"
}
}).then(function(result) {
console.log("RETURN: " + JSON.stringify(result)); // Here is where I see that JSON data
}, function(error) {
alert("Error: " + error);
});
}, function(error) {
console.log(error);
});
}
And here is the returned JSON:
{
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [null],
"transformResponse": [null],
"params": {
"access_token": "EAAS8ChUdfHEBALdJimUl5TA1sfWGZAZBv8lxlRlpcSaMhKo1NQX5JEgVuTjjpYP4agdZBZCXO0vwFJs0kLXr5CEz2h35JPZAhls9ZBVyyuwfQFlfWQkFDyGMVxsZBmGZA0s6F6XO97HpJRd7c7iZCuwEHhZAKfnMdoKerT0s5HHPW3xAZDZD",
"fields": "first_name,last_name,gender,picture,locale",
"format": "json"
},
"url": "https://graph.facebook.com/v2.2/me",
"headers": {
"Accept": "application/json"
},
"withCredentials": true
},
"statusText": ""
}
Anybody has an idea of what's wrong?

Resources