为了从OpenMRS获取数据,我需要从Java script调用OpenMRS REST API。下面是我的java脚本代码:
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);
}其中YWRtaW46QWRtaW4xMjM是我的base64编码的用户名:here所解释的密码。如果我没有在代码中放入授权行,并使用Firebug检查web应用程序,它将返回预期的401未授权状态。但是,如果我放入授权,则不会返回任何内容,并且在firebug中也看不到任何响应。如果我直接在浏览器上检查URL,页面会要求输入用户名和密码,在给出正确的凭据后,它会正常返回数据。所以我在应用程序的java脚本中提供http身份验证时遇到了一些问题。我也考虑过解释here的方法,但没有成功。有人能帮我授权来自javascript的http请求吗?
发布于 2016-08-08 23:20:47
下面是另一个类似但不同的示例,说明如何设置用于授权目的的头部,但不是使用JQuery和AJAX。
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);
})下面也是如何使用xhr而不是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);当心跨站点域请求(如果您请求的令牌不在本地主机上或您当前工作的域内),因为您将需要CORS。如果您确实遇到了跨域问题,请确保您已经启用了来自see this tutorial for help的CORS请求。
https://stackoverflow.com/questions/22413921
复制相似问题