CORS - 不使用JSONP的跨域AJAX,允许在服务器上使用Origin

时间:2013-06-26 11:09:29

标签: javascript ruby-on-rails ajax ember.js cross-domain

我在同一台服务器上有两个独立的应用程序,其中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);
    }
});

3 个答案:

答案 0 :(得分:9)

如果启用CORS,则无需使用JSONP。

Access-Control-Allow-Origin: http://www.example.com

如果在响应中设置了此标头,那么正常的XmlHttpRequest将能够像访问同一个域一样访问响应。检查此标头是否设置正确。

如果您使用的是jquery A CORS POST request works from plain javascript, but why not with 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://”的网址导致问题,在“http://”前面解决问题

答案 1 :(得分:0)

您可以在 Rails 5 中使用rack-cors,将其设置为允许所有网址。

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

答案 2 :(得分:0)

在跨域环境中,我建议使用JSONP而不是CORS,因为许多免费主机不支持跨域CORS。它在working examples中有详细介绍 - 包括JSONP和CORS。