简体   繁体   English

如何使用javascript从REST API发送请求并接收响应?

[英]How do I send request and recieve response from REST API using javascript?

I have a local server running on my computer which has an in-built REST API. 我的计算机上运行的是本地服务器,该服务器具有内置的REST API。 the base url of api is: http://127.0.0.1:8090/ehr/api/v1 . api的基本网址是: http : //127.0.0.1 : 8090/ehr/ api/ v1 Now I want to make a client application for this server using this api. 现在,我想使用此api为此服务器创建客户端应用程序。 To log in this server, the api url is baseurl/login with POST method. 要登录此服务器,API URL为baseurl /使用POST方法登录。 It takes username, password and organization as parameters and returns an auth token in json if the login is successful. 如果登录成功,它将用户名,密码和组织作为参数,并在json中返回auth令牌。 Now I want to create a form in html and javascript which will ask the username, password, organization and log in the user if response is an auth token, otherwise if the response in an error instead of token, user will not be able to log in. What should be the html and javascript code for this form? 现在,我想用html和javascript创建一个表单,该表单将询问用户名,密码,组织并登录用户(如果response是auth令牌),否则,如果响应是错误而不是令牌,则用户将无法登录in。此表单的html和javascript代码应该是什么? I typed the following code to output the auth token but it showed no result. 我键入以下代码以输出auth令牌,但未显示任何结果。 even the console log is empty. 即使控制台日志为空。

<html>
<body>
    <div class="login">
    <h1>Login</h1>
    <form method="post">
        <input type="text" name="u" placeholder="Username" id="username" required="required" />
        <input type="password" name="p" placeholder="Password" id="password" required="required" />
        <input type="text" name="p" placeholder="Organization" id="organization" required="required" />
        <button type="submit" onclick="loginfunc()">Let me in.</button>

    </form>
    </div>
    <script>
        function loginfunc(){
            var baseurl = "http://localhost:8090/ehr/api/v1";
            var funcurl = "/login";
            var username = document.getElementById("username");
            var password = document.getElementById("password");
            var organization = document.getElementById("organization");
            var url = baseurl+funcurl+"?username="+username+"&password="+password+"&organization="+organization
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open( "POST", url, true); // false for synchronous request
            xmlHttp.send( null );
            var response = JSON.parse(xmlhttp.responseText);
            document.write(response)
        }
    </script>

</body></html>

edit: I changed the login function based on suggestions to this: 编辑:我根据以下建议更改了登录功能:

function loginfunc(){
                var baseurl = "http://localhost:8090/ehr/api/v1";
                var funcurl = "/login";
                var username = document.getElementById("username");
                var password = document.getElementById("password");
                var organization = document.getElementById("organization");
                var url = baseurl+funcurl+"?username="+username+"&password="+password+"&organization="+organization;
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.onreadystatechange = function () {
                    if(xmlHttp.readyState === XMLHttpRequest.DONE && xmlHttp.status === 200) {
                        console.log(xmlHttp.responseText);
                    }
                };
                xmlHttp.open( "POST", url, true); // false for synchronous request              
                xmlHttp.send( null );
                document.write(xmlHttp.responseText);
            }

but now I get 401 unauthorized error at xmlHttp.send() function. 但是现在我在xmlHttp.send()函数中收到401未经授权的错误。 I can't understand why as when I make request to same url using a REST client like insomnia, it works fine and returns auth token. 我不明白为什么当我使用失眠之类的REST客户端向相同的URL请求时,它工作正常并返回auth令牌。

The request you're making to the server is asynchronous, so your code cannot just take the response immediately. 您对服务器的请求是异步的,因此您的代码不能仅立即获取响应。 This is done using a callback: 这是使用回调完成的:

xmlHttp.onreadystatechange = function () {
  if(xmlHttp.readyState === XMLHttpRequest.DONE && xmlHttp.status === 200) {
    console.log(xmlHttp.responseText);
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Koa2和koa-router将REST api的GET响应发送到React客户端? - How do I send GET response of REST api to React client using Koa2 and koa-router? 如何使用JavaScript MQTT将arduino的消息作为文本接收到我的网页 - How do i recieve message from my arduino to my webpage as a text using javascript MQTT 如何使用 javascript 将来自 rest 响应的数据用于 ag-grid? - How do I use data from a rest response into ag-grid using javascript? 如何下载我从 HTTP 响应(axios PUT 请求)收到的 .zip 文件 - How to download .zip file that i recieve from a HTTP response (axios PUT request) 如何从Javascript / React发送AJAX请求并在Python REST API中接收数据 - How to send AJAX request from Javascript/React and receive data in Python REST API 如何在 PHP 中向通过 javascript fetch API 发出的请求发送响应? - How to send a response in PHP to a request made through the javascript fetch API? 如何使用Request-Promise将一个API的响应作为另一个API中的请求参数传递 - How do I pass the response of one API as a request param in another API using Request-Promise 通过 javascript 向 REST API 发送 POST 请求 - Send POST request to REST API via javascript 如何在Ajax请求上发送JavaScript? - How do I send javascript on ajax request? 如何在 angular 中发送 REST 响应到 html? - How do I send REST response to html in angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM