EWS - A token was not recognized in the JSON content - javascript

I try to send an email via EWS using Javascript and the REST API.
The OAuth is not the problem so far.
The problem is, if I try to send the email, the Server sends this response:
"{"error":{"code":"RequestBodyRead","message":"Invalid JSON. A token was not recognized in the JSON content."}" (taken from Chrome Debug Console).
Here my Javascript, where the error occurs:
function mailIsRaus(token) {
var gottenParam = JSON.stringify(token);
var jsonObj = JSON.parse(gottenParam);
var leToken = jsonObj['access_token'];
//This is the Token from Active Directory
leToken = "Bearer " + leToken;
var Message = {
"Message": {
"Subject": "TESTING REST API EWS",
"Body": {
"ContentType": "Text",
"Content": "IT WORKED. The EWS is working my friend."
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "johndoe#something.com"
}
}
]
},
"SaveToSentItems": "true"
};
//eMailData = JSON.stringify(eMailData);
$.ajax({
type: 'POST',
beforeSend: function (request) {
request.setRequestHeader("Authorization", leToken);
request.setRequestHeader("Content-Type", "application/json");
},
data: Message,
url: 'https://outlook.office.com/api/v2.0/me/sendmail',
success: function (e) {
console.log('Email sent');
console.log(e);
},
error: function (message) {
console.log(message);
}
});
}
I strictly sticked to MSDN and now, I have no clue, why this error occurs.
If I comment out the "setRequestHeader" I get an error 401 unauthorized.
The token ist correct.
The scope is also correct.
Maybe I made an simple mistake in the "var Massage" or something...

I found the solution by myself.
I had to uncomment the following line of code to:
eMailData = JSON.stringify(eMailData);
Now it is working fine.

Related

Sendgrid integration with SAPUI5 app returns '400 Bad Request' on POST but works on Postman

I'm developing a cordova hybrid app that utilizes UI5 library. I need to be able to send as Email from the app so I decided to use Sendgrid API and, since I had issues with the NodeJS module, I'm creating an AJAX request. I've previously tested the request with Postman, being able to successfully send emails. But, as I tried to do the same request from the app, I've stumbled upon a status '400 Bad Request' without further information. Here goes the code snippet:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.sendgrid.com/v3/mail/send",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer [REDACTED]",
"cache-control": "no-cache"
},
"processData": false,
"data": {
"personalizations": [
{
"to": [
{
"email": "myemail#gmail.com"
}
],
"subject": "Contato do app"
}
],
"from": {
"email": "anotheremail#gmail.com"
},
"content": [
{
"type": "text/plain",
"value": formatEmail //variable with the email text
}
]
}
}
$.ajax(settings).then(
function success(response, status) {
dialog.close();
if (status == 202){
MessageBox.confirm('Mensagem enviada com sucesso', {
actions: [sap.m.MessageBox.Action.OK],
onClose: function(sAction){
that.onNavBack()
}
});
} else {
MessageBox.error('Erro!');
}
},
function fail(data, status){
dialog.close();
MessageBox.error('Request failed. Returned status of ' + status + ' DEBUGDATA: ' + JSON.stringify(data));
}
);
I really can't figure out the reason as to why this happens because the snippet generated by Postman is very similar to my code. Any help would be highly appreciated!
Thanks in advance
usually HTTP 400 means bad request and it means that you're passing the wrong parameters to the HTTP POST request.

rescuegroup/Petfinder jQuery API requests

I am currently trying to get API responses from the two following API's. All of the sample code on their website is in PHP and asks for a token and token SSH, while they only give you an API key. Very lost trying to get requests to pull. The closest I've gotten is an error that says the following:
{status: "error", message: "Unable to read your data; it might not be in json format."}
here is my JS:
jQuery.get({
url: 'https://api.rescuegroups.org/http/v2.json',
type: 'post',
contentType: 'application/json',
data: {
apikey: 'XXXXXXX',
objectType:'animals',
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Any help is greatly appreciated. Really want to avoid having to learn PHP as I'm still very new to JS.
the problem is that you are not passing it as json.
this is json format.
let dataObject = {
data: {
apiKey: "xxxx"
}
};
let data = JSON.stringify(dataObject);
{
"data": {
"apikey": "xxx"
}
}
then pass data as your data.
After trying it with Postman the request went through.
Obviously I don't have the api key
{
"status": "error",
"message": "Error with your login credentials",
"messages": {
"generalMessages": [
{
"messageID": "1101",
"messageCriticality": "error",
"messageText": "Error with your login credentials."
}
],
"recordMessages": []
}
}

AJAX Jquery Call returning 401 (unauthorized) - API Call

So I'm creating a GET request to this API: https://immense-depths-6983.herokuapp.com/search/.
A sample URL to test in your browser is: https://immense-depths-6983.herokuapp.com/search?search=94305
The username is "admin" and password is "password".
Running the sample URL in the browser gives me a popup asking for the authentication and upon entering it correctly, I get back a JSON response text.
However, when I run this on code, it doesn't work. I've scoured the web for answers and each solution doesn't work. I've tried admin:password#url, passing in the username and password as data parameters in the GET request, and even using the BTOA hash thing to pass that to the web server. Alas to no results. I've attached my code I'm using right now - hope some good soul can help me out of this problem.
My error (EDIT 1):
---------CODE--------------
render() {
var url = this.props.url;
var zip = '94305';
// var zip = this.props.zip;
// create the prop type later with built in functionality
var query = zip + this.props.query;
var username = "admin";
var password = "password";
var ret_data = textbookApi(url, query, username, password);
console.log("after");
// if data is null, ignore
// else
// this.setState({textbooks: ret_data});
return (
<div>
</div>
);
}
}
export default Search;
function makeBaseAuth(user, pswd) {
var token = user + ':' + pswd;
var hash = "";
if (btoa) {
hash = btoa(token);
}
return "Basic " + hash;
}
function textbookApi(url_link, query, username, password) {
// console.log("INSIDE");
console.log(makeBaseAuth(username, password));
$.ajax({
type: "GET",
url: url_link,
data: {
'search' : query
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', makeBaseAuth(username, password));
},
success: function(data) {
console.log("WORKS!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(data);
return data;
}.bind(this),
error: function(xhr, status, err) {
console.error(url_link, status, err.toString());
}.bind(this)
});
}
Try to send your http header with username and password as Basic Authentication method
I tried this method on Jquery ajax call
var settings = {
"async": true,
"crossDomain": true,
"url": "https://immense-depths-6983.herokuapp.com/search?search=94305",
"method": "GET",
"headers": {
"authorization": "Basic YWRtaW46cGFzc3dvcmQ=",
"cache-control": "no-cache",
"postman-token": "54733c33-4918-811b-3987-69d6edeaa3a0"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Make sure you enabled cross domain access form your server side.... & not getting any error related to that.
Pass the username & password as basic authentication in ajax http
method.
It worked for me Output :
-[
-{ "id" : 0, "title" : Basic Electronics: An Introduction to Electronics for Science Students, "author" : Curtis Meyer, "no" : 0,
"class" : , "isbn" : 5800066848142 },
-{ "id" : 0, "title" : Programming Abstractions in C++, "author" : Jerry Cain, "no" : 0, "class" : CS 106B CS 106X, "isbn" : 1 },
-{ "id" : 0, "title" : The Mind's Machine: Foundations of Brain and Behavior, "author" : Neil Verne Watson, "no" : 0, "class" : Think,
"isbn" : 9780878939336 },
-{ "id" : 0, "title" : Physics for Scientists and Engineers: A Strategic Approach, "author" : Randall D. Knight, "no" : 0, "class" :
Physics 41, "isbn" : 9780321752918 },.... .... ...
Try https://www.base64decode.org to encode & decode
To make an AJAX request using CORS, the server needs to be configured to accept cross-origin requests, otherwise ajax call will fail.
Read these article to know more about it:
https://zinoui.com/blog/cross-domain-ajax-request
Access-Control-Allow-Origin error sending a jQuery Post to Google API's
How to get a cross-origin resource sharing (CORS) post request working
function textbookApi(url_link, query, username, password) {
// console.log("INSIDE");
console.log(makeBaseAuth(username, password));
$.ajax({
type: "GET",
url: url_link,
data: {
'search' : query
},
"error": function(xhr, error, thrown) {
console.log("Error occurred!");
console.log(xhr, error, thrown);
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', makeBaseAuth(username, password));
},
success: function(data) {
console.log("WORKS!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(data);
return data;
}.bind(this),
error: function(xhr, status, err) {
console.error(url_link, status, err.toString());
}.bind(this)
});
}

CORS: Access-Control-Allow-Origin not equal to supplied origin

I'm trying to send an email from an application using sendgrid. This shouldn't be too difficult, and with PHP I've sent emails before. In this case I want to do it in Javascript as it's part of an Ember application. The first problem is the "No 'Access-Control-Allow-Origin" message, which I tried to solve with CORS. Now I've just got a different error!
Now I'm not sure where to look for tackling this issue. The code I'm using is the following:
(function(){
makeCorsRequest('GET', mailUrl);
})();
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function makeCorsRequest(type, url) {
var xhr = createCORSRequest(type, url);
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
This gives me the error:
The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.com' that is not equal to the supplied origin. Origin 'http://localhost' is therefore not allowed access.
sendGrid CORS policy does not allow browsers to call their API (except if your are on "sendgrid.api-docs.io" domain) ... You have to send email from your server,
but if just for test or development purpose you can use my demo on github
https://github.com/itisnajim/sendgrid-nodejs
post your data to
http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.com
Ajax example:
let urlStr = "http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.com";
const msg = {
"personalizations": [
{"to": [{"email": "example1#mail.com"}]}
],
"from": {"email": "example2#mail.com"},
"subject": "subject example",
"content": [{"type": "text/plain", "value": "example body text"}]
};
$.ajax({
url: urlStr,
type: 'post',
data: JSON.stringify(msg),
dataType: 'json',
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer API_KEY_HERE")
},
success: function(data){
//console.log(data);
//OK: Mail sent!!
},
error: function( jqXhr, textStatus, errorThrown ){
//console.log( errorThrown, textStatus, jqXhr );
if(jqXhr.status === 202 || jqXhr.status === "202"){
//OK: Mail sent!!
}else
console.error("Mail not sent! Err:"+JSON.stringify(errorThrown))
}
})
It looks like you're calling the SendGrid API from an Ember app running in your browser? If so, you probably shouldn't be (for a number of security reasons).
You'll want to make an AJAX request to a server running on your own domain, and have your server
validate that the request is legitimate, and
call the SendGrid API to send the email
Exposing your SendGrid API key, and calling the API directly from a browser exposes your SendGrid account to potential abusers.
For the server-side API call, check out SendGrid's API Clients. You shouldn't need to write the API calls yourself.

How to send data to a web Service Using Winj.xhr

I am new in Winjs coding I have data in a list .
and i want to send that data to my json Web Service .
I have a success to call to web service and i have the response so the web service is
working but the data doesn't seem to be sent. I dont know how to declare the data.
I have many data to sent like(username,first_name,last_name,password) to my Register.json
The Register.json have this response after the execution:
{
"format":
"json",
"success":
false,
"errors":
["User name is empty"],
"result":
null
}
so i m sure that data doesnt be sent
function Register() {
var dataArray = [
{
username: "Marley",
first_name: "dog",
last_name: "ded",
password: "pdre4252d"
}];
WinJS.xhr({
url: "my_Base_URL/Register.json",
type: "post",
headers: { "Content-type": "application /x-www-form-urlencoded" },
data: dataArray
// data:JSON.stringify(dataArray)
}).done(
function complete(result) {
if (result.status === 200) {
console.log("Success: Response Text: " + result.responseText);
}
else {
console.log("Fail:Response Text: " + result.responseText);
}
},
function error(error) {
console.log("error");
},
function progress(result) {
}
);
}
I will be thinkful if someone give me some help.
The WinJS.xhr() is a promise wrapper around XMLHttpRequest, which means it delegates your parameters to an XMLHttpRequest object and returns a WinJS.Promise object. The parameters may not be delegated correctly so play with adding and empty string for a username and such. Otherwise you can mimic the same functionality by creating your own WinJS.Promise with an XMLHttpRequest inside.

Categories

Resources