如何使用GET/POST方法与minehutAPI/服务器进行交互 [英] How to use GET/POST methods to interact with minehutAPI/server

查看:236
本文介绍了如何使用GET/POST方法与minehutAPI/服务器进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用minehut API,并在查看了文档之后(

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.

第1部分-获取信息

例如:我想获取有关服务器的信息,它说使用GET https://api.minehut.com/server/{server-id} 我将如何从中获取例如playercount的信息,这样我就可以将该信息提供给我的代码并显示在我的网站上. 文档中还提到了Required headers:,这些是什么,我该如何使用它们?

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?

第2部分-发送信息

现在说例如我要运行命令,文档说要使用POST /server/{Server ID}/send_command.它还提到了Required标头,说它需要 Content-TypeAuthorizationx-session-id 我将如何发送字符串,以便它将使用POST运行命令

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

推荐答案

您需要使用GET/POST方法发送或接收数据的是XMLHttpRequest对象.

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();

或者在POST请求的情况下:

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");

在某些情况下,可以完成预检请求(尤其是使用自定义请求标头),并且该请求可能会失败.为了避免这种情况,您可以尝试使用用户名/密码来调用开头.对于跨域请求,应发出访问控制请求,以允许设置cookie.

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;

这篇关于如何使用GET/POST方法与minehutAPI/服务器进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆