javascript - CORS 不再工作

标签 javascript php ajax

我遇到了一个奇怪的问题,一天又一天我的 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/

相关文章:

javascript - 检查数组中任何元素的总和是否等于给定值

php - Symfony 2.8 app no style 加载资源失败

jQuery: serialize() 表单和其他参数

php - 设置后立即在同一页面获取 ID

php - 从 URL 中提取站点标题

python - 我如何处理 Django 中的 spotify api 身份验证重定向 uri?

ajax - 从 JQuery 向 Web API 进行 POST 时出现问题

javascript - Javascript/Jquery/Gamequery 中的每像素碰撞检测

javascript - AngularJS/Parse.com : $scope. currentUser 变量未更新

javascript - 使用 jquery 动态选择基于 json 数据的选项