XMLHttpRequest 无法加载,不存在“Access-Control-Allow-Origin”标头(无法读取 JavaScript/jQuery 中的 Ajax 响应)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28104251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:30:49  来源:igfitidea点击:

XMLHttpRequest cannot load, No 'Access-Control-Allow-Origin' header is present (Unable to read Ajax response in JavaScript/jQuery )

jqueryajaxcross-domain

提问by Venkatesh Achanta

I'm sending an Ajax request to server using jQuery, below is the code snippet.

我正在使用 jQuery 向服务器发送 Ajax 请求,下面是代码片段。

$.ajax({                
                type: 'POST',
                url: "https://store.example.com/account?",                
                data: "cf=cw&operation=update"
            })

Definitely, “requested page” and “Ajax request's URL” are in same domain. Still, Am seeing specified error message in browser console and unable read response with JavaScript/jQuery. Please help me here.

当然,“请求的页面”和“Ajax 请求的 URL”在同一个域中。尽管如此,我还是在浏览器控制台中看到了指定的错误消息,并且无法使用 JavaScript/jQuery 读取响应。请在这里帮助我。

Error message: XMLHttpRequest cannot load https://store.example.com/account?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://store.example.com' is therefore not allowed access.

错误消息:XMLHttpRequest 无法加载 https://store.example.com/account?。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“ http://store.example.com”。

采纳答案by Pavan Andhukuri

Are the requesting page and requested URL are in the same domain. Can you try accessing the url using relative path?

请求页面和请求的 URL 是否在同一个域中。您可以尝试使用相对路径访问 url 吗?

$.ajax({                
            type: 'POST',
            url: "/account?",                
            data: "cf=cw&operation=update"
        })

回答by Outlooker

AJAX Requests are only possible if port, protocol and domain of sender and receiver are equal,if not might lead to CORS. CORS stands for Cross-origin resource sharing and has to be supported on the server side.

AJAX 请求只有在发送方和接收方的端口、协议和域相等时才可能,否则可能导致 CORS。CORS 代表跨域资源共享,必须在服务器端支持。

Solution

解决方案

JSONP

JSONP

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy.

JSONP 或“带填充的 JSON”是一种通信技术,用于在 Web 浏览器中运行的 JavaScript 程序,以从不同域中的服务器请求数据,由于同源策略,典型的 Web 浏览器禁止这种技术。

Example

例子

$.ajax({
    type: 'POST',
    url: "https://store.example.com/account?",
    dataType: 'jsonp',
    success: function (data) {
        //code
    }
});

Hope this gives you an idea mate.. :)

希望这给你一个想法伙伴.. :)