Try to catch all of my contacs using google api v3: ERROR - javascript

I need help. I try to catch all of contacs from Google Api V3, Auth2, but it returns this error:
GET https://www.google.com/m8/feeds/contacts/default/full?callback=jQuery171029…+gsession&issued_at=1379496709&expires_at=1379500309&_aa=0&_=1379496719602 401
(Token invalid - AuthSub token has wrong scope)
First I Sign in Google +, and then i try to do the authorization in Google Contacts:
function myContacts() {
var config = {
'client_id': clientId,
'scope': 'https://www.google.com/m8/feeds',
};
gapi.auth.authorize(config, function () {
var authParams = gapi.auth.getToken(); // from Google oAuth
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full',
dataType: 'jsonp',
type: "GET",
data: authParams,
success: function (data) {
alert("success: " + JSON.stringify(data))
},
error: function (data) {
console.log("error: " + JSON.stringify(data))
}
})
});
}
Is this the correct way to do this?
Thank you

Append access_token into url as request parameter with the token fetched after authorization, instead of sending it to data.

you can't do an hxr (ajax) request given the CORS restriction from goolge.com.
you can use this library to achieve this though. It solves the Oauth login/retrieving contacts from gmail)
http://eventioz.github.io/gcontacts/

Related

CORS policy error when trying to call custom search analyzer of azure search from ajax or browser

CORS policy error when trying to call custom search analyzer of azure search from ajax or browser
I have azure search service enabled on azure account. Trying to search queries with azure search from client call or ajax and which is happening very smoothly. I have some requirement to analyze search query before searching actual search text, so I have created a custom analyzer which when I am trying to call from browser or ajax I am getting CORS policy error on browser.
Tried already:
I have enabled CORS for index in which i have created the custom analyzer
I have used npm library that is azure-search.min.js having function to call for analyzer (client.testAnalyzer): https://www.npmjs.com/package/azure-search-client
//Sample 1:
var index2 = AzureSearch({
url: k2,
key: k1,
version: "2019-05-06"
});
var analyzerdata = {
"text": searchTextData,
"analyzer": sessionStorage.getItem('analyz')
}
index2.testAnalyzer("fastampsearchindex", analyzerdata, function (err,
tokens) {
if (!isNullorEmpty(tokens)) {
//phrases = data.map(x=>x.token);
}
});
//Sample 2:
var urlTokenizer="https://mysearchurl.search.windows.net/indexes/indexname/analyze?api-version=2019-05-06";
var analyzerdata = {
"text": searchTextData,
"analyzer": sessionStorage.getItem('analyz')
}
$.ajax({
type: "POST",
url: url2,
dataType: 'json',
crossDomain:true,
data: analyzerdata,
headers: {
"api-key": k1,
"Content-Type":"application/json"
},
success: function (response) {
console.log(response);
},
error: function (xhr, status, message) {
$('.loader').css('display', 'none');
var err = "Error " + " " + message;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
toastr.warning(err);
}
});
analyzer should be called from browser instead of application to avoid round trip to azure search service via web app service where application is hosted

Calling Outlook API to Add event to outlook calendar using ajax call

I need to Add an event from my database to outlook calendar for which I have been trying to make an ajax call to the outlook auth API first which looks like this
$scope.authorizeOutlook = function () {
let redirect = 'http://localhost:51419';
let clientId = 'xxx';
var authData = 'client_id=' + clientId + '&response_type=code&redirect_uri=' + redirect + '&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Fcalendars.readwrite%20&state=12345';
debugger
$.ajax({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
type: 'POST',
host: 'https://login.microsoftonline.com',
contentType: "application/x-www-form-urlencoded",
contentLength: "600",
data: authData,
success: function (response) {
debugger;
alert(response.status);
//alert("success");
},
error: function (response) {
alert(response.status);
//alert("fail");
}
});
}
But I am getting response status as 0. What does that mean? Where am I doing it wrong?
If you use Oauth2.0, you need to add " token-type: Bearer ".
Reference from:
Get access tokens to call Microsoft Graph

How to disable 'withCredentials' in api call using node.js only (https package)

I'm using a node.js script that load in-built https package. When using it I get error:
XMLHttpRequest cannot load [constructed-api-url]. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
I'm using node.js 4.4.3, and its https api docs does not really mention anything about withCredentials.
The script being used is this one.
Is there anyway to set the xhr call's withCredentials to false using node.js https?
I am looking to something analogous to this jquery ajax call (just focusing on the xhr field):
$.ajax({
type: 'POST', async:true,
url: 'https://someapp.constructed.url/token',
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + appInfo
},
success: function (result) {
var token = result.access_token;
//…
},
error: function (req, status, error) {
if (typeof(req) != 'undefined') {
var msg = status || req.responseJSON.error;
//…
}
}
});
There is another very similar example, but this is related to the request package, which I don't want to include in dependencies. Beside, my used script is already using https.
So the answer was there all the time, after all:
After a bit of research, found that node's https package uses practically same options as http, including the withCredentials option (not documented in node's http/https, but part of xhr documentation). It was a matter of including the url option within the options object along the withCredentials option, and then pass the options object as parameter for https.get.
And the constructed code would be more or less as follows (focus on the options variable):
var options = {
url: 'https://my.domain.com/api/endpoint',
withCredentials: false
}
var querystring = '?key=' + [_my_api_key];
var param1 = '&' + [paramKey] + '=' + [paramValue];
var datos;
options.url += querystring;
options.url += param1;
https.get(options, function (res) {
res.on('data', function (data) {
datos += data;
});
res.on('end', function () {
try {
var data = JSON.parse(datos);
} catch (e) {
console.error('Unable to parse response as JSON', e);
}
});
}).on('error', function (e) {
console.error('An error occurred with the request:', e.message);
callback(e.message);
});

CORS error when trying to post message

I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular

Ajax calling WEB API throwing a Parser Error

So I am trying to make an AJAX call to get JSON information from a WEB API. The WEB API method seems to be working properly and when I try to access it via Fiddler, it returns a result:
When I try to access it via JQUERY AJAX, it fails and says that there is a parser error. Below is my AJAX call:
$.ajax({
url: 'http://example:port/api/values/',
type: 'GET',
dataType: 'jsonp',
success: function (data) {
alert("works");
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
Below is my WEB API Method:
[System.Web.Http.HttpGet]
public List<Users> Get()
{
List<Users> user= (from m in new DataAccessLayer.MapRepository().GetUsersRelatingTo("UserName")
select new CommonLayer.Views.Markers
{
ID= m.UserID,
}).ToList();
return users;
}
I would appreciate any sort of tip, thanks!
Edit: Below is more information on the error:

Categories

Resources