How to write http request in javascript? - javascript

I know it can be done but i am no good with http request at all. I have a very specific one i need to write. The code is here but i dont know which line to return to my app for the response.
var request = new XMLHttpRequest();
request.open('POST', 'https://v2.api.xapo.com/oauth2/token');
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Authorization', 'Basic YTVlMGExMTViYTc1MThjYzphNWUwYTExNWJhNzUxOGNjYTVlMGExMTViYTc1MThjYw==');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = "grant_type=client_credentials&redirect_uri=https://myURI.com";
request.send(body);
This is what im trying to do.
curl --include --request POST --header "Content-Type: application/x-www-form-urlencoded" --header "Authorization: Basic MYKEYHERE[auth]" --data-binary "grant_type=client_credentials&redirect_uri=MYREDIRECTURI" 'https://v2.api.xapo.com/oauth2/token'
The api for this is here

please see the following code :
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
first you define an instance of XMLHttpRequest() that will do the http request for you
second the method xhttp.onreadystatechange = function()will be listening to state change that means it will be executed once an http responde is returned
third xhttp.open method will determine your connection config for example here we set a property "POST" then determining the link you want to post to it along with the variables you want to post like this :
enter the link
put ? mark
put the variable name
put =
put the varible value
put & mark and repeat the steps 3 4 5 if you want to post more variable else put nothing .
fourth the method xhttp.send()will start the http request to the server and once the response is gotten the xhttp.onreadystatechange = function()will be called then you can get the content of the response with xhttp.responseText
I hope this example is clear

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

Unable to send JSON object to XMLHttpRequest

I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");
However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.
var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send(JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
}));
You're sending very different information in your two calls. Some sample code:
var _stringify = JSON.stringify({
'apikey' :'ee6915d4ee4b4df66bba82277e3',
'firstname' : 'Kumar',
'lastname' : 'Sunder',
'phone':'5557773334'
});
console.log(_stringify);
var _orig = "apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456"
var _encoded = encodeURI(_stringify);
console.log(_orig);
console.log(_encoded);
when your original string is printed to the console log, it looks as you would expect:
apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456
when the result of JSON.stringify is printed to the console, it returns:
{"apikey":"ee6915d4ee4b4df66bba82277e3","firstname":"Kumar","lastname":"Sunder","phone":"5557773334"}
That is, it comes complete with lots of extra double quote marks and left and right brackets. If you want to send all of that as a string (as in your initial example), you would need to URI encode the result of the JSON.stringify call. This is what happens with the "_encoded" variable, which contains:
%7B%22apikey%22:%22ee6915d4ee4b4df66bba82277e3%22,%22firstname%22:%22Kumar%22,%22lastname%22:%22Sunder%22,%22phone%22:%225557773334%22%7D
You are sending via a POST action, but then sending the data via a url string. If you want to send it that way you need to set it to GET.

Post request gets cut off

I have a problem with my post request in javascript.
I have the following code for sending the post request
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
//stuff
}
};
xhttp.open("POST", "/deleteUser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + username);
And in my node.js express application i receive it like this
var username = req.body.username;
Now this works perfect with normal characters (numbers and letters). But when i tried
>df)(*&&^%$
as username it gets cut off to
>df)(*
I suspect it is because of the &.
My question: How do i prevent it from getting cut off.
Thanks in advance!
You need to convert the username parameter into a URI safe string, using xhttp.send("username="+encodeURIComponent(username));

How to send JSON response from python server to the javascript using ajax call

elif self.path == "/recQuery":
r = requests.get('http://example.com') # This returns some json from a request to another server.
print r.json()
self.wfile.write(r.json())
.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
console.log(http.responseText);
How can i send data from python server to javascript using ajax call. The one i am using does not return anything in the console. Can you please tell me what i am doing wrong here. I need send the response of what i get from requests.get method to the ajax call. The json should be returned to the ajax call in response. Problem is with the self.wfile.write method, When i use this i dont get anything on javascript side.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
I was not fetching the response onreadystatechange. So this works for me. Thanks !

XMLHttpRequest for connecting to a secure url

I am using example code which I found here:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_post2
I want to get a JSON string from an endpoint that requires authentication.
How do I specify my ID / Pass with the request being made to the endpoint ( Is there a HTTP header which I can use which would ask me to authenticate )?
What is a workaround for connecting to the url which might need us to authenticate?
How can I specify to use a SSL certificate for getting response?
< script >
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
} < /script>

Categories

Resources