简体   繁体   中英

unable to get the rest response with javascript

I've the below HTML code.

<html>    
<head>
    <script>
        function someFunction() {
            var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
            var win = window.open(URL, "_blank", strWindowFeatures);
            win.document.write(UserAction());
            win.document.close();
        }

        function UserAction() {
            var xhttp = new XMLHttpRequest();
            xhttp.open("GET", "myUrl", false);
            xhttp.setRequestHeader("Authorization", "Basic " + Base64.encode("myId:myPwd"));
            xhttp.setRequestHeader("Content-type", "application/json");
            xhttp.send();
            var response = JSON.parse(xhttp.responseText);
            console.log(response);
            return response;
        }
    </script>
</head>

<body>
    <input type="button" onclick="someFunction()" />
</body>
</html>

Here when I click on the button it is opening a new window and there it is showing the error as below screenshot.

在此处输入图片说明

when I see the console.log() I see the message as below in my new(popup) window.

Not allowed to load local resource: file:///C:/Users/rakesh.keerthi/Desktop/nodePractice/AlexaNode/function%20URL()%20%7B%20[native%20code]%20%7D

in my actual html page I get the error as

sample.html:17 XMLHttpRequest cannot load file:///C:/Users/rakesh.keerthi/Desktop/nodePractice/AlexaNode/myUrl. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. UserAction @ sample.html:17 someFunction @ sample.html:8 onclick @ sample.html:26 sample.html:17 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/rakesh.keerthi/Desktop/nodePractice/AlexaNode/myUrl'. at UserAction (file:///C:/Users/rakesh.keerthi/Desktop/nodePractice/AlexaNode/sample.html:17:19) at someFunction (file:///C:/Users/rakesh.keerthi/Desktop/nodePractice/AlexaNode/sample.html:8:32) at HTMLInputElement.onclick (file:///C:/Users/rakesh.keerthi/Desktop/nodePractice/AlexaNode/sample.html:26:53)

When I try the same thing in postman it works, unable to understand where am I going wrong. please let me know how can I fix this.

Thanks

If you are using google chrome you could try running it with the

--allow-file-access-from-files

switch enabled

您要么必须从具有您的AJAX所调用资源的同一域中运行它,要么必须设置跨域Ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM