我正在做一个CORS尝试尝试自动完成功能,就像从我的本地服务器到其他在线的测试一样。此服务器具有在我尝试访问的文件夹中配置的基本身份验证。所以我已经完成了ajax函数(我正在使用JQuery UI自动完成功能),并且我已经配置了php脚本来为我返回一个JSON。一切从同一台服务器工作正常。CORS尝试,PHP不修改响应头
这是我做了什么:
$(function() {
$("#field").autocomplete({
minLength: 1,
source: function (request, response) {
console.log(request.term);
$.ajax({
type: 'POST',
url: url,
data: {
'idautor': 417,
'lat': 43.56,
'lon': -5.96,
'etiqueta': request.term
},
crossDomain: true,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", btoa(username + ":" + password));
},
success: function(data) {
response($.map(data["pines"], function(item) {
return {
value: item["nombre"],
label: item["nombre"],
idsitio: item["idsitio"],
autor: item["autor"]
}
}));
}
}).then(function(data) {
console.log('data', data);
},
function(err) {
console.log('err', err);
});
},
select: function (event, ui) {
alert("El sitio con id "+ui.item.idsitio+" y autor "+ui.item.autor+" ha sido pulsado.");
}
})
});
问题是,当我试图从我的本地服务器,基本上我说的是我得到以下错误的跨域HTTP请求使用它在我的浏览器控制台:
的XMLHttpRequest无法加载URL回应预检要求不 通过访问控制检查:没有“访问控制允许来源”标头 出现在所请求的资源。原产地'http://localhost'是 ,因此不允许访问。响应HTTP状态代码401
所以我研究了这个问题,我发现几个promissing和简单的解决方案,我的问题。我试着头添加到PHP文件:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
header("Access-Control-Allow-Headers: accept, authorization, content-type");
也试过将它们添加到我的.htaccess
文件,但没有成功可言。我仍然遇到同样的错误。关于我错过了什么的任何线索?
为了以防万一以及进一步的信息,这是我发送请求时,我的XHR连接记录,在那里我看不到我已经手动添加在PHP中的新标头。
我有一个类似的问题,我的PHP服务器,并通过添加从这个答案的代码得到它的工作:http://stackoverflow.com/questions/18382740/cors-not-working-php/18399709#18399709试试吧出。 – noviewpoint
@noviewpoint我已经尝试过,仍然是一样的,不知道为什么,但有些东西否认我的标题修改或只是覆盖它... – Asur