CORS error when trying to post message - javascript

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

Related

How to send a POST request with Advanced Custom Fields data

I'm trying to send a post request to the rest api with some custom fields. THis is my code
let newCharacter = {
'title': $('.create-char-name').val(),
'acf': {
'char_class': $('#char-class').val(),
'char_subclass': $('#char-subclass').val(),
'char_level': $('#char-level').val()
},
'status': 'publish'
}
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
},
url: spbk_data.root_url + '/wp-json/wp/v2/character/',
method: 'POST',
data: newCharacter,
success: (response) => {
console.log("congrats");
console.log(response);
},
error: (response) => {
console.log("Sorry");
console.log(response);
}
});
The request goes through without any problems, but when I check the json, the "acf" field returns false.
I'm using the acf to wp api plugin, if that information is useful.
The only info I found about this issue was this post, but I don't really understand what the answer meant. I tried adding xhr.setRequestHeader('Content-Type', application/json); (I also tried with lower case initials), below the nonce, like the post seems to suggest, but that returns this error:
"{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}"
Try something like below:
function NewCharacter(){
this.title;
this.acf;
this.status;
}
function CharInfo(){
this.char_class;
this.char_subclass;
this.char_level;
}
var charInfo = new CharInfo();
charInfo.char_class=$('#char-class').val();
charInfo.char_subclass=$('#char-subclass').val();
charInfo.char_level=$('#char-level').val();
var newCharacter = new NewCharacter();
newCharacter.title=$('.create-char-name').val();
newCharacter.acf=charInfo
newCharacter.status="publish";
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
},
url: spbk_data.root_url + '/wp-json/wp/v2/character/',
method: 'POST',
data: JSON.stringify(newCharacter),
success: (response) => {
console.log("congrats");
console.log(response);
},
error: (response) => {
console.log("Sorry");
console.log(response);
}
});
Yeah, I'm kinda dumb. I tried another plugin to make the bridge between acf and the rest api, and it worked.
It came to my mind many times to try another plugin, but I thought "they do the same thing, there's no point in trying that". It goes to show that you shouldn't just brush off solutions that seem too obvious or stupid.

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

Ionic v1 AngularJS $http POST request not working

I'm trying to send a POST request to a rest API, but I don't seem to able to do it correctly, I don't know if it's the syntax, or what it could be, I've tried many different ways but nothing seems to work. Here's is some pictures of the service being consumed by POSTMAN (everything works fine here).
The Headers
And the body with the response
But then when I try to consume the service via AngularJS, it keeps sending me erros messages, the localhost server even detects that there is a request, because I can see it on the Eclipse's console, but it doesn't run through the debugger with togglebreakpoints and it does with POSTMAN.
This is one of the many attempts to send a $http request
var json = { practiceId: 1 };
$http({
method: "POST",
url: "https://localhost/GetAppointmentTypes",
data: JSON.stringify(json),
headers: {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
}
})
.success(function(data) {
$ionicPopup.alert({
title: 'WORKING'
});
})
.error(function (errResponse, status) {
if(status == 403){
$ionicPopup.alert({
title: '403'
});
}
});
But then
And here is another attempt
var url = 'https://localhost/GetAppointmentTypes';
var parameter = JSON.stringify({practiceId:1});
var headers = {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
};
$http.post(url, parameter, headers).then(function(response){
$ionicPopup.alert({
title: 'WORKING'
});
}, function(response){
$ionicPopup.alert({
title: ' NOT WORKING '
});
});
And the response
Note: the $window.localStorage['token'] is working correctly. I have tried so many things I don't even know what I'm doing wrong now, might be a syntax error, but then ERROR 403 wouldn't be showing.
EDITED (ADDED)
And the Response Variable

How to add text to the body of a CasperJS thenOpen() POST request

I need to write a script inside of datorama.com to access pardot.com. Pardot does have an API that requires a request that has a request inside the body as
POST: https://pi.pardot.com/api/login/version/3
message body: email=&password=&user_key=
Right now here is my code:
phantom.casperPath = casperPath;
phantom.injectJs(casperPath + "/bin/bootstrap.js");
var casper = require('casper').create({
verbose: true,
logLevel: 'debug'
});
casper.start().thenOpen('https://pi.pardot.com/api/login/version/3',{
method: 'post',
content: {
'text' : 'email=<myemail>&password=<password>&user_key=<userKey>'
}
}, function(response) {
this.echo(this.getHTML());
});
casper.run();
I can tell that it is getting through to the server because it is responding this.echo(this.getHTML()); "Login Failed" . I am using the right email/password/user_Key because i am pulling that from the API Console for pardot and it is working there.... So I believe the issue is I am not setting the body of the request correctly.
So does anyone know a way to set the body on the request?
casper.open() or casper.thenOpen() don't understand the content setting. You probably wanted to use data:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: 'email=<myemail>&password=<password>&user_key=<userKey>'
}, function() { ... });
Don't forget to use encodeURIComponent() on the email, password and user key parameters if you build the string yourself.
You can also pass an object:
casper.start()
.thenOpen('https://pi.pardot.com/api/login/version/3', {
method: 'post',
data: {
email: '<myemail>',
password: '<password>',
user_key: '<userKey>'
}
}, function() { ... });
If you expect something else than HTML from the API, then you should use casper.getPageContent() instead of casper.getHTML().

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

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/

Categories

Resources