Enable CORS via JavaScript (Phonegap)

5

I'm creating a Phonegap application that consumes a Web Service (Web Service) API, and I need to access an external domain. Searching through the web I found that I had to enable CORS via JavaScript to be able to access other domains. In this way I would like to know how I would do this.

Below is a search code made by the app.

function find()
{
  var urlAl = 'http://*********/api/Produtos';
  header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

  $.ajax({
    type : "GET",
    dataType : "jsonp",
    url : urlAl,
    success: function(data){
      alert(data);
    },
    error: function()
    {
      alert("erro");  
    }
});
    
asked by anonymous 24.02.2015 / 20:41

1 answer

4

No PhoneGap

From other StackOverflow questions (translated freely into Portuguese):

  

Does PhoneGap support cors?

     

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:

  

Cors and PhoneGap Apps

     

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 }) .

    
24.02.2015 / 21:08