No PhoneGap
From other StackOverflow questions (translated freely into Portuguese):
RE:
Yes it supports, all you have to do is add this line to your config.xml
file:
<access origin=“http://example.com” />
You can also do this:
<access origin=“*” />
Another answer:
With PhoneGap you can only make XHR requests directly to remote servers and they should simply work. The Cross-domain
policy does not apply to PhoneGap (for several reasons, basically because your App is running from the file://
URI on the device).
Please keep in mind that you will need to set up a whitelist for your Apps to access external domains. Please check out this link:
I hope this clarifies your doubt; below are instructions for if this is a request in the browser.
In the browser
It would be necessary for you to change your server to support cors, by adding a Header Access-Control-Allow-Origin
to the domain that Phonegap rolled over - can be a wildcard ( *
) to accept all sources. Depending on the type of request you need to make, you will need to implement "pre-flight" routes, which are only OPTIONS
routes to your application, that respond with headers. This should not be difficult to do, but it will depend on your server.
In Node.js, for example, you could use the cors
module and solve the problem on the server with one or two lines:
app.use(cors());
app.options(‘*’, cors());
That done, you just have to change your request to enable CORS on the client-side ( documentation ):
$.ajax({
// …
crossDomain: true,
});
If you wanted to pass / receive cookies from the server, you would need to make another modification:
$.ajax({
// …
xhrFields: {
withCredentials: true,
},
});
In this case the server would also have to include the header Access-Control-Allow-Credentials
. In the case of Node.js, it would suffice to change cors()
to cors({ credentials: true })
.