How to make http authentication in REST API call from javascript

I need to call the OpenMRS REST API from a Java script to get data from OpenMRS. Below is the java script code:

function myfunction(){ var xhr = new XMLHttpRequest(); xhr.open("GET", "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John", false); xhr.setRequestHeader("Authorization: Basic YWRtaW46QWRtaW4xMjM"); xhr.send(""); alert(xhr.status); } 

Where YWRtaW46QWRtaW4xMjM is my basic coded username: password, as described here . If I do not put the authorization string in the code and test the web application using Firebug, it returns 401 the unauthorized status that is expected. But if I set authorization, nothing returns, and in firebug I also do not see any answer. If I check the URL directly in the browser, the page asks for the username and password and returns the normal data after providing the correct credentials. So I get some problem with providing HTTP authentication right from the java script application. I also looked at the methods explained here , but no luck. Can someone help me resolve an HTTP request directly from javascript?

+1
source share
1 answer

Here is another similar but different example of how to set up the header for authorization purposes, but use jQuery and AJAX instead.

 var token = "xyz" var url = "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John" $.ajax({ url: url, beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Bearer " + token) }, }) .done(function (data) { $.each(data, function (key, value) { // Do Something }) }) .fail(function (jqXHR, textStatus) { alert("Error: " + textStatus); }) 

Below is an example of how you can get the access token using xhr instead of AJAX.

 var data = "grant_type=password& username=myusername@website.com &password=MyPassword"; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("POST", "https://somewebsite.net/token"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.setRequestHeader("client_id", "4444-4444-44de-4444"); xhr.send(data); 

Beware of cross-site domain requests (if you are requesting a token that is not on the local host or in the domain you are currently working in), as this will require CORS. If you encounter a cross-domain access issue, see this tutorial for reference , make sure you also include CORS requests from the API.

+1
source

Source: https://habr.com/ru/post/1240866/


All Articles