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) {
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.
Kevin source share