我遇到了一个奇怪的问题,一天又一天我的 AJAX 请求网站不再工作。
我现在正在努力让它工作,但找不到问题。
这是我的javascript: 基本上它非常简单,它检索 ip 地址,然后将其发送 (POST) 到存储它的站点。
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://dashboard.inofec.nl/ip', true); // If specified, responseType must be empty string or "text" xhr.responseType = 'text'; xhr.onload = function () { if (xhr.readyState === xhr.DONE) { if (xhr.status === 200) { // console.log('R = ' + xhr.response); // console.log('RT= ' + xhr.responseText); tip = xhr.responseText; var formData = new FormData(); formData.append('ip', tip); formData.append('uri', turl); formData.append('id', dataId); var request = new XMLHttpRequest(); request.open("POST", "https://dashboard.inofec.nl/visits"); request.send(formData); // console.log('IP = ' + tip); // console.log('URL = ' + turl); console.log('ID = ' + dataId); } else { console.log('ERROR !'); } } } xhr.send(null);
我现在在服务器上添加了这个以避免使用通配符
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] != '') { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Max-Age: 1000'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); }
当我只使用
header('Access-Control-Allow-Origin: '); I got the error: Cross-Origin-request blocked: CORS-header ‘Access-Control-Allow-Origin’ does not match ‘, *’).
有了新的标题,我得到了
CORS-header ‘Access-Control-Allow-Origin’ does not match ‘http://www.inofec.nl, *’).
但是当我检查 header 时,我发现它以正确的 header 响应。
Access-control-allow-headers
Content-Type, Authorization, X-Requested-With access-control-allow-methods
GET, PUT, POST, DELETE, OPTIONS access-control-allow-origin http://www.inofec.nl, *
最佳答案
Yvo Cilon 让我思考了多重值(value)。 并为我指明了正确的方向。
我搜索了 header ,发现网络服务器上已经设置了一个 header ,我将其添加到我的代码中。
我删除了网络服务器中设置的 header ,以控制它的使用方式和时间。
感谢分享您的想法。
关于javascript - CORS 不再工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47883146/