问题
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
回答1:
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;
来源:https://stackoverflow.com/questions/58302369/how-to-use-get-post-methods-to-interact-with-minehutapi-server