Javascript XMLHttpRequest对预检错误的响应

时间:2018-07-20 17:12:45

标签: javascript xml xmlhttprequest

我正在尝试使用纯JavaScript进行简单的get请求,但我有一段时间没有这样做了。我必须通过基本身份验证才能获得此请求。在邮递员中效果很好,用户界面使输入用户通行证变得简单。我在给我这个“预检响应具有无效的HTTP状态”错误的代码中做什么?我没有正确设置请求吗?我正在使用chrome跨域扩展程序并已打开。所以不要以为这是问题。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="data">

    </div>


<button onclick="dashboard()">click me</button>
    <script>

        function dashboard() {
            var request = makeHttpObject();
            // var form_id = BO.getDataId();
            // var app_id = app.getUID();
            var user = "blah";
            var password = "blue"
            var app_id = "f4asdsd4sasdgrer5e78b-fcsdasssd77s-4ef4-8asefxzxcze207be8";
            var link = `https://found.mainstream.org/authentixate-basic/secure/1/data/${app_id}/F_Form1`;

            request.open("GET", link, true);
            request.setRequestHeader("Authorization", "Basic " + btoa(user +":"+ password));


            request.onreadystatechange = function () {
                if (request.readyState == 4)
                    getAttachmentInfo(request.responseText);
            };
            request.send(null);


            function makeHttpObject() {
                try {
                    return new XMLHttpRequest();
                } catch (error) { }
                try {
                    return new ActiveXObject("Msxml2.XMLHTTP");
                } catch (error) { }
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } catch (error) { }

                throw new Error("Could not create HTTP request object.");
            }

            function getAttachmentInfo(data) {
                var parser, xmlDoc;

                if (window.DOMParser) {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(data, "text/xml");
                } else {
                    // Internet Explorer 
                    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                    xmlDoc.async = false;
                    xmlDoc.loadXML(data);
                }
                for (i = 0; i < xmlDoc.getElementsByTagName("F_Form1").length; i++) {
                    // var FilesObj = {
                    //     "attachmentFileName": xmlDoc.getElementsByTagName("F_Attachment")[i].childNodes[1].firstChild.nodeValue,
                    // }
                    //console.log("data",xmlDoc.getElementsByTagName("F_Form1")[i].attributes)
                    console.log("data",xmlDoc.getElementsByTagName("F_Form1")[i].attributes[3])
                }

            }
        }

    </script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

原来是CORS问题。代码在生产环境中效果很好,但在我的本地环境中却不是