I have started with the minehut API, and after looking at the docs (see a copy here) it uses get and post.
As a newbie to javascript etc I dont know how it works.
Part 1 - Get Info
for example: I want to get info about a server, it says to use GET https://api.minehut.com/server/{server-id}
How would i get for example playercount from it so that i can give that info to my code and display it on my website.
Required headers: is also mentioned in the docs, what are these and how do i use them?
Part 2 - send info
Now say for example i want to run a command, the docs say to use POST /server/{Server ID}/send_command. It also mentions Required headers saying it needs
Content-Type,
Authorization and
x-session-id
how would i send a string so that it would use POST to run a command
What you need to send or receive data using GET/POST methods is XMLHttpRequest object.
var server_id = "EXAMPLE_ID";
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(this.readyState == 4){
// Data sent back available in this.responseText
// For example:
var recData = this.responseText;
// further handling
}
}
req.open('GET', 'https://api.minehut.com/server/' + server_id, true);
req.send();
Or in case of POST request:
req.open('POST', 'https://api.minehut.com/server/' + server_id + '/send_command', true);
req.setRequestHeader("Content-Type", "pplication/x-www-form-urlencoded");
req.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
req.setRequestHeader("HeaderNameExample", "ItsValueExample");
req.send('optionalVar=sentData&foo=bar&etc");
In some cases preflight request can be done (especially with custom request headers) and the request might fail. To avoid that you might try invoking the opening with user/password instead. For cross domain request Access-Controll request should be made which allows for cookies to be set.
req.open("GET", url, true, username, password);
req.open("POST", url, true, username, password);
req.withCredentials = true;
Related
I've created a ClickListener which is supposed to make a POST request to my server. Most of the times, the POST request is made but sometimes, it fails to make a POST request no matter how many times I try. Can anyone help me understand what the issue is and how to resolve it? This is my code where I'm handling that:
$("#Button11").on("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/addtolist", true);
xhr.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded",
"Access-Control-Allow-Origin",
"*"
);
var parameter = "dc=deal1";
xhr.send(parameter);
window.location.href = "/final_page.ejs";
});
The issue
XMLHttpRequest.send() is an asynchronous method, that mean this method only ask the request to be sent but it will not be done instantly. Most of the time, this does not matters, but in your script, you redirect the user right after it, so, sometime, the user is redirected before the request is sent.
The solution
You have to wait the request to be done before redirecting the user, thankfully, XMLHttpRequest have a method to achieve it. It is the XMLHttpRequest.onload() method. So you can update your script to :
$("#Button11").on("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/addtolist", true);
xhr.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded",
"Access-Control-Allow-Origin",
"*"
);
var parameter = "dc=deal1";
xhr.send(parameter);
xhr.onload = function(){
window.location.href = "/final_page.ejs";
};
});
As mentioned in the comments, JQuery also have an integrated solution for making request, I recommend you reading it's documentation to have an even better solution.
Your location change is killing your Ajax before it finishes
Also why not use the much simpler $.post now you have it?
None of your headers are needed and the auth header is not even allowed to be set by you
$("#Button11").on("click", function() {
$.post("/addtolist",{"dc":"deal1"},function() {
window.location.href = "/final_page.ejs";
})
});
I have a function which sends a POST request to my node.js server, but the headers, params, cookies and everything is empty. I've checked my browser console and it was sent, there's just nothing in it. Can anyone help my identify the problem? (email and pass isn't empty, either.)
function sendPostRequest() {
const email = document.getElementById('email').value;
const pass = document.getElementById('pass').value;
var params = 'email=' + email + "&pass=" + pass;
var http = new XMLHttpRequest();
http.open("POST", "http://localhost:3000", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
}
Follow the steps to fix the error
Check network tab in browser developer console whether it's passing the data or not if not the problem is in front end.
If that is true, then check backend and print the request body if there it's not coming then it's backend
I'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
I used ajax to send the data. I was successful in implementing it using two different approaches:
1) Using method 'POST' and sending data in send() method by setting requestheader.
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send("userName=xyz&password=abc");
2) Using method "POST" and appending parameter values in the URL as:
var xmlHttp = getXMLHttpRequest();
var url="login.do?userName=xyz&password=abc";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send();
Since this is an ajax call, URL will not be visible in the browser window, so I wanted to know which approach is better and why?
Thanks in advance
Here is W3 recommendation for you.
That pretty much says what exactly you need to do.
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead.
Though it is saying post, internal meaning of it is to keep the URL clean.
Apart from the given two ways, if I were you, I prefer clean codes (imagine 10 query param).
var data = new FormData();
data.append('userName', 'xyz');
data.append('password', 'abc');
var xmlHttp = getXMLHttpRequest();
var url="login.do";
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
// Done. Do nothing.
}
}
xmlHttp.send(data);
Putting data into the URL's query parameters doesn't make it a GET request. A POST request is a POST request; the difference is between sending data in the URL or sending it as POST body. There's no fundamental difference between both in this case, the data is equally (non) visible for anyone who cares to look.
The only arguable difference in security is that the URL will likely be logged by the server and/or proxies, while body data usually isn't. But then again, you're already sending the data to the server you presumably trust, so even that doesn't make much of a difference. And the server(s) could be logging the body as well if they wanted to.
Semantically I'd send the data in the POST body, but that's not because of security.
I am currently trying to access the parameters of a POST request using Google Apps Script. I can logger the params object using e.parameter though i cannot seem to access the keys of the object by by using e.parameter.name.
XMLHttpRequest
var http = new XMLHttpRequest();
var url = "myappURL";
var params = JSON.stringify({employeeStatus: "Active", name: "Henry"});
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
// call back function
} // end callback
http.send(params);
Google Apps Script
function doPost(e) {
if (typeof e !== 'undefined') {
Logger.log(e.parameter.name); // does not work (undefined)
} // end if
} // end doPost
There are subtle quirks with the different ways data is posed via http. For instance I notice that you are using Content-type "application/x-www-form-urlencoded" when the usual header for json data is Content-Type: application/json.
I added a line that just returns the contents of the e variable so you can see what is returned.
I used curl to debug it with the following command.
curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec
The response I received was:
{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}}
You can see that in my case the json was returned in the contents field rather than the parameters.
You could try this with your script to see what you get. You could also try changing the Content-Type.
After Further testing I think you would be better submitting your fields a form data rather than json. I have been able to get the paramer back by amending your javascript to:
var http = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec";
var params = "employeeStatus='Active'&name='Henry'";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState==4) {
//alert the user that a response now exists in the responseTest property.
console.log(http.responseText);
// And to view in firebug
// console.log('xhr',xmlhttp)
}
} // end callback
http.send(params);