I've now spent some time trying to get the JavaScript below working in my API (c#).
I run perfectly in JavaScript, but I get access denied as a response in my c# code.
JS :
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
document.getElementById('KundeListing').innerHTML = this.responseText;
console.log(this.responseText);
}
});
xhr.open("GET", "https://plus.dnb.com/v1/search/typeahead?searchTerm=Wal&countryISOAlpha2Code=US");
xhr.setRequestHeader("Authorization", "Bearer " + Token);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.withCredentials = false;
xhr.send();
But When trying usingRestSharp; I am getting errors
'You are not currently authorized to access this product'
public string Get(string Token)
{
var client = new RestSharp.RestClient("https://plus.dnb.com/v1/search/typeahead?searchTerm=Wal&countryISOAlpha2Code=US");
var request = new RestRequest(Method.GET)
{
UseDefaultCredentials = true
};
request.AddHeader("accept", "application/json");
request.AddHeader("authorization", "Bearer " + Token);
IRestResponse response = client.Execute(request);
return response.ToString();
}
Related
How can I best format my POST request for the Cisco API CompressedClientLog?
https://developer.cisco.com/docs/finesse/#!compressedclientlog%e2%80%94post-compressed-log-to-finesse/compressedclientlogpost-compressed-log-to-finesse
CompressedClientLog—Post Compressed Log to Finesse
var data = new FormData();
var logObj = '<ClientLog><logData>This is some logged data for the log file</logData></ClientLog>';
data.append("logData", logObj);
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log("Gadget is now engaged" + this.responseText);
}
});
xhr.open("POST", "https://finesse1.xyz.com/finesse/api/User/finadmin/CompressedClientLog");
xhr.send(data);
Response is:
<ApiErrors>
<ApiError>
<ErrorType>Parameter Missing</ErrorType>
<ErrorData>logData</ErrorData>
<ErrorMessage>Missing logData in the ClientLog object</ErrorMessage>
</ApiError>
</ApiErrors>
Where am I going wrong?
Dont worry about the api_key as I am doing this just for practice. Earlier it was showing CORS error so i disabled it in chrome. But now its giving me GET https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972 400 error.
function sendRequest () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972",true);
xhr.setRequestHeader("Accept","application/json");
xhr.setRequestHeader("Authorization", "Bearer {i6LdgRRNDolECGnS0Q7MQf5c3-nNV9rciQdmNy6x0jBFGtBv8DlnCSd2erPEOlKOb6m63MFMj0UzEEINB58fmdZBgy0bW75qfrb4BtRQxZGFcmqczb3vFXjK6G9qYXYx}");
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
console.log(users)
}
}
xhr.send(null);
}
use it
function sendRequest () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972",true);
xhr.setRequestHeader("Accept","application/json");
xhr.setRequestHeader("Authorization", "Bearer i6LdgRRNDolECGnS0Q7MQf5c3-nNV9rciQdmNy6x0jBFGtBv8DlnCSd2erPEOlKOb6m63MFMj0UzEEINB58fmdZBgy0bW75qfrb4BtRQxZGFcmqczb3vFXjK6G9qYXYx");
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
console.log(users)
}
}
xhr.send(null);
}
the { and } used for env and variable in postman (or other softwares usually)
in raw http request :
GET https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972
Accept: application/json
Authorization: Bearer i6LdgRRNDolECGnS0Q7MQf5c3-nNV9rciQdmNy6x0jBFGtBv8DlnCSd2erPEOlKOb6m63MFMj0UzEEINB58fmdZBgy0bW75qfrb4BtRQxZGFcmqczb3vFXjK6G9qYXYx
postman have a feature that export requests in different programming language, use it to see efferent (link)
I am getting the raw data of the drafted from Gmail API "get" method and sending it using Gmail API "send" method.
'var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/id?
format=raw&alt=json&access_token=' + token;
url = url.replace("id", emailId);
var x = new XMLHttpRequest();
x.open('GET', url , true);
x.send();
x.onload = function() {
var jsonRes = JSON.parse(x.response);
sendEmail(jsonRes.raw);
}
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json&access_token=' + token;
params = "raw=" + raw;
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}`
I am getting 401 status.
If I am sending this raw data from API page itself, then it is sent successfully. Therefore the raw data is correct.
I am missing something while sending the email. Please help!
A 401 error means "invalid credentials", most likely because your token has expired or isn't valid.
The Google API explorer and Google Javascript libraries take care of the token for you (generally), but if you're calling the service endpoints directly with XMLHttpRequest(), you'll have to manage the token yourself.
If you want to go that route, here are the details you have to implement: https://developers.google.com/identity/protocols/OAuth2
You can try things out in the "Oauth2 playground": https://developers.google.com/oauthplayground/
Thank you for all responses.
I sent the email using the following code-
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send';
var params = JSON.stringify({'raw': raw});
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}
}
There were two mistakes I rectified-
1. The token was sent in URL as well as header. It should be sent only in header.
2. The param raw was sent as String but it should be sent as a JSON object.
I have a page to show the chat messages. I need to refresh the chat body every 30 seconds to load the new messages. I have set the interval to 30 seconds , the function is running , but its not making the HTTP request. Here is my code
function loadmessages(){
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/'+ ids );
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function(){
if(this.status == 200){
var resp = JSON.parse(this.responseText);
console.log(resp.message);
}
else{
console.log(this.status);
}
request.send(null);
}
}
loadmessages();
setInterval(function(){
loadmessages()
}, 30000);
Consistent indentation matters. You're putting request.send(null); inside the request.onload function, so of course it never gets sent in the first place. Try putting it outside, instead:
function loadmessages() {
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/' + ids);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.responseText);
console.log(resp.message);
} else {
console.log(this.status);
}
}
request.send(null);
}
I'm creating a javascript library for a project im doing that makes rest calls based on params you feed it. This is the second day of the project and I'm looking for advice. If I set my request to be async it returns my request but i can't access the object value, if I set it to false in the call it returns an object.
I read the stack articles on async js request, and I can't seem to wrap my head around call backs and promises.
this works:
request.open("DELETE", url, false);
this doesn't:
request.open("DELETE", url, true);
(function(window){
function defineCynergi(){
var Cynergi = {};
Cynergi.get = function(url){
var request = makeHttpObject();
request.open("GET", url, false);
request.send(null);
return JSON.parse(request.responseText);
}
Cynergi.delete = function(url){
var request = new XMLHttpRequest();
request.open("DELETE", url, false);
request.setRequestHeader('Accept', 'application/localhost.com:3000+json; version=1');
request.send();
deleteStatus = request.statusText;
return deleteStatus;
}
Cynergi.insert = function(url, data){
var request = new XMLHttpRequest();
request.open("POST", url, false);
request.setRequestHeader('Accept', 'application/localhost.com:3000+json; version=1');
request.send(JSON.stringify(data));
sentStatus = request.statusText;
return sentStatus;
}
Cynergi.update = function(url, data){
var request = new XMLHttpRequest();
request.open("PATCH", url, false);
request.setRequestHeader('Accept', 'application/localhost:3000+json; version=1');
request.send(JSON.stringify(data));
updateStatus = request.statusText;
console.log(request);
return updateStatus;
}
return Cynergi;
}
if(typeof(Cynergi) === 'undefined'){
window.Cynergi = defineCynergi();
}
})(window);
function makeHttpObject() {
try {return new XMLHttpRequest();}
catch (error) {}
try {return new ActiveXObject("Msxml2.XMLHTTP");}
catch (error) {}
try {return new ActiveXObject("Microsoft.XMLHTTP");}
catch (error) {}
throw new Error("Could not create HTTP request object.");
}
You should do something like this:
var request = new XMLHttpRequest();
request.open('GET', yourURI, true); // true = async
request.send();
request.onreadystatechange(function () {
if(request.readyState === 4){
/*ENTER CODE THAT SHOULD BE EXECUTED WHEN REQUEST IS DONE
(OPTIONAL)*/
switch(request.status) {
case 200: //DO STUFF
case 404: //DO OTHER STUFF
}
}
});
Or this:
var request = new XMLHttpRequest();
request.open('GET', yourURI, true);
request.addEventListener('load', function () {
//CODE THAT SHOULD BE EXECUTED WHEN SUCCES.
});
request.addEventListener('error', function () {
//CODE THAT SHOULD BE EXECUTED WHEN ERROR RESPONE.
});
request.send();