In the Phonegap
From other Stackoverflow questions (translated freely into English):
RE:
Yes it supports, all you have to do is add that line to your file config.xml
:
<access origin=“http://example.com” />
You can do that too:
<access origin=“*” />
Another answer:
With Phonegap you can only make XHR requests directly to remote servers and they should simply work. The policy of Cross-domain
does not apply to Phonegap (for several reasons, basically because your App is running from the URI file://
in the device).
Please keep in mind that you will have to set up a Whitelist for your Apps to access external domains. Please check this link:
http://docs.phonegap.com/en/1.8.0rc1/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide
I hope this clarifies your doubt; below are instructions for if this was a request in the browser.
In the browser
It would require you to change your server to support Cors by adding a Header Access-Control-Allow-Origin
for the domain that Phonegap runs on top of - could be a wildcard (*
) to accept all origins. Depending on the type of request you need to make, you will need to implement "pre-flight" routes, which are only routes OPTIONS
for your application, which respond with headers. This shouldn’t be hard to do, but will depend on your server.
In Node.js, for example, you could use the module cors
and solve the problem on the server with one or two lines:
app.use(cors());
app.options(‘*’, cors());
This done, simply change your request to enable CORS in 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 that case the server would also have to include the header Access-Control-Allow-Credentials
. In the case of Node.js, it would be enough to change cors()
for cors({ credentials: true })
.
What platform are you developing for? The solution varies (the problem is not quite CORS), according to the documentation: http://docs.phonegap.com/en/1.8.0rc1/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide
– bfavaretto
This question already exists on the site does not help you? If not, what is the difference of your problem? It is important to show that you have searched the site before posting similar articles and show how your case differs. http://answall.com/questions/5959/cors-no-nodejs-sem-o-uso-de-frameworks
– Nigini
@Nigini if it is the same question then it would be better to mark as duplicate, so the question is blocked but not deleted and still references the question that would be the "first".
– Guilherme Nascimento
Opa @Guilhermenascimento. Yeah, I’m not sure, because the other question uses a framework not mentioned here. In this case I preferred Gabriel to evaluate and improve the question.
– Nigini