以下是我正在尝试进行基本身份验证的服务电话。我检查了多个博客无法找到解决方案。
当我收到以下错误时,有人可以帮我解决这个问题:
XMLHttpRequest无法加载
预检的响应包含无效的HTTP状态代码401
我在开发人员选项的网络标签中找不到基本身份验证。
function() {
"use strict";
var APIservice = function($http, $base64) {
var getDetails = function(postData) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
$http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET,PUT,POST,DELETE,OPTIONS";
$http.defaults.headers.common['Access-Control-Allow-Headers'] = "Content-Type, Authorization, Content-Length, X-Requested-With";
$http.defaults.headers.common['Content-Type'] = undefined;
console.log($http.defaults.headers.common.Authorization);
//console.log($http.defaults.headers.common.Authorization);
return $http.get('http://52.74.68.202:8080/rest/v1/step/all')
.then(function(response, headers, config) {
console.log(response);
return response;
});
};
return {
getDetails: getDetails
}
}
var module = angular.module('expframework');
module.factory("APIservice", APIservice);
module.run(['$http', '$base64', function($http, $base64) {
var authdata = $base64.encode('test:test');
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}]);
module.config(['$httpProvider', '$base64', function($httpProvider, $base64) {
var authdata = $base64.encode('test:test');
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}])
}();
它适用于Safari和模拟器,但不适用于Chrome和Firefox
请帮我解决这个问题。提前谢谢。
答案 0 :(得分:2)
由于你的服务器扔了401,我猜它试图验证预检请求。来自https://stackoverflow.com/a/15734032/1225328:
W3 spec for CORS preflight requests明确指出应排除用户凭据。
[...]
只需让服务器(本例中的API)响应
public class Transaction { public int Id { get; set; } //this is internally used, not need to have anything [Required] [DataType(DataType.Currency)] public decimal Amount { get; set; } [Required] public int CheckingAccountId{ get; set; } public virtual CheckingAccount CheckingAccount { get; set; } //this is to force the entity framework to recognize this as a foreign key }
请求,而无需进行身份验证。