将Content-Type设置为json时,AJAX返回错误

时间:2019-03-01 21:27:56

标签: javascript ajax

我正在为自己编写一个简单的ajax库,由于某种原因我遇到了错误。这是返回{}

的代码示例

var Ajax = /** @class */ (function () {
    function Ajax() {
    }
    Ajax.send = function (params) {
        var xhttp = new XMLHttpRequest();
        params.error = params.error || function () { };
        params.callback = params.callback || function () {
            if (this.readyState == 4 && this.status == 200) {
                params.success(this);
            }
            else if (this.readyState == 4) {
                params.error(this);
            }
        };
        xhttp.onreadystatechange = params.callback;
        xhttp.open(params.method, params.url, params.async || true);
        for (var header in params.headers) {
            xhttp.setRequestHeader(header, params.headers[header]);
        }
        //xhttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xhttp.send();
    };
    return Ajax;
}());
Ajax.send({
    method: "GET",
    url: "https://rectangular-nephew.glitch.me/",
    success: function (e) {
        document.write(e.responseText);
    },
    error: function (e) {
        document.write("Error: " + e.status);
    }
});

一切正常,直到我将内容类型设置为application/json

var Ajax = /** @class */ (function () {
    function Ajax() {
    }
    Ajax.send = function (params) {
        var xhttp = new XMLHttpRequest();
        params.error = params.error || function () { };
        params.callback = params.callback || function () {
            if (this.readyState == 4 && this.status == 200) {
                params.success(this);
            }
            else if (this.readyState == 4) {
                params.error(this);
            }
        };
        xhttp.onreadystatechange = params.callback;
        xhttp.open(params.method, params.url, params.async || true);
        for (var header in params.headers) {
            xhttp.setRequestHeader(header, params.headers[header]);
        }
        
        ///Here it is
        xhttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xhttp.send();
    };
    return Ajax;
}());
Ajax.send({
    method: "GET",
    url: "https://rectangular-nephew.glitch.me/",
    success: function (e) {
        document.write(e.responseText);
    },
    error: function (e) {
        document.write("Error: " + e.status);
    }
});

我不知道为什么会这样。我已经在服务器上设置了标头:

response.set("Access-Control-Allow-Origin", "*");
response.set("Access-Control-Allow-Methods", "*");
response.set("Access-Control-Allow-Headers", "*");

但是它也不起作用。 那么可能是什么问题?

错误:

  

访问“ https://rectangular-nephew.glitch.me/”处的XMLHttpRequest   来自来源“ https://www.typescriptlang.org”的信息已被CORS阻止   策略:对预检请求的响应未通过访问控制   检查:标题上没有'Access-Control-Allow-Origin'标头   请求的资源。

0 个答案:

没有答案