Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS - Cross-Domain AJAX Without JSONP By Allowing Origin On Server

I have two separate apps on the same server, with the EmberJS one trying to do cross-domain calls to my backend API.

I set up my backend API to allow cross-domain requests from that specific origin. Is there a way however, to avoid using JSONP with such a set up? $.ajax is blocking cross-domain requests before they ever get sent. If not, what is the point of CORS, which server-side I had implemented to accept requests from my JS front-end source?

EDIT

AJAX request:

$.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);
    }
});
like image 413
darksky Avatar asked Jun 26 '13 11:06

darksky


People also ask

Does Ajax need CORS?

When building complex client-side applications, at some point it usually becomes necessary to make Ajax requests to domains other than the one from which your page originated. This is especially true if you are part of a large enterprise with distributed sub-domained resources.

How do I send a request without CORS?

There is no way to do it in a browser (for security reasons). There is no way. You will have to involve a 3rd agent (either a proxy or your own server) that you can request the data from and it can fetch it from the web site for you and then return it to you.


1 Answers

There is no need to use JSONP if you enable CORS.

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

if this header is set in the response, then normal XmlHttpRequest will be able to access the response as if it is like same domain. Check whether this header is set correctly.

I hope that this link will help you if you are using jquery A CORS POST request works from plain javascript, but why not with jQuery?

Update: Example

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();

Try this in any domain, you will get response.

Update solution:

Request url without "http://" caused the problem, prepending "http://" solved the issue

like image 175
Balaji Sivanath Avatar answered Oct 02 '22 14:10

Balaji Sivanath