CORS – 不允许JSONP的跨域AJAX,允许在服务器上使用Origin
我在同一台服务器上有两个独立的应用程序,EmberJS试图对我的后端API进行跨域调用。
我设置了后端API以允许来自该特定来源的跨域请求。 但有没有办法避免在这样的设置中使用JSONP? $.ajax
在发送之前阻止跨域请求。 如果没有,CORS有什么意义,我实现了哪些服务器端接受来自我的JS前端源的请求?
编辑
AJAX请求:
$.ajax({ url: "api.lvh.me:3000/accounts/login", data: cred, type: "POST", xhrFields: { withCredentials: true }, success: function(response){ alert('succeeded!'); console.log(response); alert(response); }, failure: function(message){ alert("failed"); console.log(message); alert(message); } });
如果启用CORS,则无需使用JSONP。
Access-Control-Allow-Origin: http://www.example.com
如果在响应中设置了此标头,那么正常的XmlHttpRequest将能够像访问同一个域一样访问响应。 检查此标头是否设置正确。
我希望这个链接可以帮助你,如果你使用jquery 一个CORS POST请求工作从普通的JavaScript,但为什么不使用jQuery?
更新:示例
var xmlhttp= new XMLHttpRequest(); var url="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control"; xmlhttp.open("GET",url,false); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); xmlhttp.send();
在任何域中试试这个,你会得到回应。
更新方案:
请求没有“http://”的url导致问题,前面的“http://”解决了这个问题
您可以在Rails 5中使用rack-cors
,将其设置为允许所有URL。
Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: [ :get, :post, :put, :patch, :delete, :options, :head ] end end
在跨域环境中,我建议使用JSONP而不是CORS,因为许多免费主机不支持跨域CORS。 它在工作示例中详细说明 – 包括JSONP和CORS。