HTTP Basic Authentication in AngularJS



我正在尝试在AngularJS中调用API。API 具有username = adminpassword = admin123HTTP Basic Authentication

这就是我调用 API 的方式,

$http.get('https://example.com', {
headers: {'Authorization': 'Basic YWRtaW46YWRtaW4xMjM='}
}).then(console.log("something"));

但是,它给了我401 UnAuthorized回应。推荐的用户名和密码传递方式是什么?我正在使用AngularJS 1.

显示错误,

OPTIONS https://example.com 401 ()
Failed to load https://example.com: Response for preflight has invalid HTTP status code 401.
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"Authorization":"Basic YWRtaW46YWRtaW4xMjM=","Accept":"application/json, text/plain, */*"},"url":"https://example.com"},"statusText":"","xhrStatus":"error"}

如果您的所有请求都需要授权标头,您可能希望在更全局的级别设置授权标头。您可以通过添加

.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = '<Basic Auth Header>';
}]);

在应用配置中。为了回答您的实际问题,我认为您提供的代码没有任何特别的问题。您能否提供有关服务器端的期望以及它如何读取授权的一些信息?

最新更新