Reputation: 7921
I have a website that takes a GET request and returns a JSON. I can send the website a request using a node server and receive the correct response. However, when I try to send it using client-side javascript:
$.ajax({
url: '<myurl>',
type: 'GET',
crossDomain: true,
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
I get the error
XMLHttpRequest cannot load <myurl>. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'http://localhost:8080' is
therefore not allowed access.
When I try changing the datatype to jsonp by adding dataType: 'jsonp',
to the ajax request, I get the error
Uncaught SyntaxError: Unexpected token :
The chrome developer console tells me the error is coming from the script <myurl>&callback=jQuery21309685717469546944_1423379667604&_=1423379667605
, and when I open the script I find the JSON response I am trying to retrieve! but I guess somehow it's being interpreted as a javascript function. Any way to resolve this? I have read many SO answers and tried many approaches to no avail.
Upvotes: 0
Views: 1460
Reputation: 707218
You will need to change something server-side to make this work from a browser. The server will need to either support JSONP or CORS in order to access it cross domain.
You cannot make client-only changes to make JSONP or CORS work - the server must cooperate.
With CORS, the right headers must exist on the http requests between client and server in order to permit the browser to process the cross origin request.
With JSONP, it is a completely different type of response from the server that makes JSONP work (data wrapped in a javascript script) so the server has to produce this other type of response in order for JSONP to work.
If you think your server already supports cross origin requests via CORS, then there is probably an error in the implementation somewhere.
The cross origin restrictions are implemented inside the browser in order to protect users using the browser. Such restrictions are not enforced by a server so servers are not limited to which origins they can connect to.
Upvotes: 1