CORS error with jquery
我目前正在使用CloudAppAPI开发一个项目,我正在使用jQuery。这是我的代码:
1 2 3 4 5 6 7 8 9 | $.ajax({ headers: {"Accept":"application/json"}, type: 'GET', url: 'http://cl.ly/2wr4', crossDomain: true, success: function(data, textStatus, request){ console.log(data); } }); |
当我运行这个程序时,我得到200个OK响应,而这个错误出现在firefox中:
1 | Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://cl.ly/2wr4. This can be fixed by moving the resource to the same domain or enabling CORS. |
谷歌Chrome的这个错误是:
1 | XMLHttpRequest cannot load http://cl.ly/2wr4. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. |
没有任何记录到控制台。请告诉我如何修复这个错误?
谢谢。
CORS(跨源站资源共享)是一个HTML5功能,允许一个站点访问另一个站点的资源,尽管其域名不同。
CORS的W3C规范实际上非常好地提供了一些简单的响应头示例,例如键头、
如果您正在寻找有关如何在各种常见Web服务器上设置CORS的具体信息,请访问启用CORS共享网站。网址:http://enable-cors.org/
基于您上面给出的URL,我认为您在该服务器上没有控制权。因此,它将根本不起作用。
即使已启用CrossDomain:true,服务器也应返回所需的头,如:
这是一个有效的服务器响应;CORS特定的头是加粗的
HTTP响应:
1 2 3 4 | Access-Control-Allow-Origin: http://xyzcom Access-Control-Allow-Credentials: true Access-Control-Expose-Headers: FooBar Content-Type: text/html; charset=utf-8 |
你可以尝试的一件事是:
[cc lang="javascript"]$.ajax({headers: {"Accept":"application/json
An important note for those newer coders is that everything on http://enable-cors.org/server.html assumes you have a server running. If you're new, like I was originally, these type of answers don't help.
If you've just made some code on your computer, CodePen, etc - you can't configure this.
There's an important difference between server-side and client-side scripting - your jquery is running on the client side (that is, the users computer / browser) and as such there's no such thing as setting the headers there.
I finally started making progress with this issue when I set up my own server and my own PHP files (PHP is server-side, as such its processed on the server - not the browser) and was able to start making requests just fine.
Adding this for anyone who is being drowned in answers involving the
要修复错误,需要在服务器上启用CORS。客户机希望看到CORS头被发回以便允许请求。它甚至可能发送一个飞行前请求,以确保头部在那里。
您可以为访问您的服务器的一个、多个或所有域启用CORS服务器端。配置因服务器类型而异。
有关详细信息,请参阅以下页面:http://enable-cors.org/server.html
您已经在上面的请求中启用了CORS请求,所以客户端应该已经设置好了。