Enabling CORS in a RESTFull Silex server, working with a phonegap/cordova applications


This days I’m working with phonegap/cordova projects. I’m using topcoat and AngularJs to build the client side and Silex for the backend. Cordova applications are “diferent” than a common web application. Our client side is normally located inside our mobile device (it’s also possible to use remote webviews). Our cordova application must speak with our backend. The easiest way to perform this operation is to use a REST. AngularJS has a great tool to connect with RESTFull resources. Silex is also great to build RESTFull services. I wrote a couple of posts about it.

With the first request form our AngularJS application (into our android/iphone device) to our Silex application, we will face with CORS. We cannot perform a request from our “local” phonegap/cordova application to our remote WebServer. We cannot do it if we don’t allow it explictily. With Silex it’s pretty straight forward to do it. We can use the event dispatcher and change the request with after handler.

$app->after(function (Request $request, Response $response) {
    $response->headers->set('Access-Control-Allow-Origin', '*');
});

We can do more strict, setting also “Access-Control-Allow-Methods” and “Access-Control-Allow-Headers” headers but only with this header we can work properly with our RESTFull Silex application from our phonegap/cordova application.

About these ads

About Gonzalo Ayuso

Web Architect specialized in Open Source technologies. PHP, Python, JQuery, Dojo, PostgreSQL, CouchDB and node.js but always learning.

Posted on December 16, 2013, in cordova, phonegap, silex, Symfony and tagged , , , , . Bookmark the permalink. 4 Comments.

  1. You do realize that using “*” basically defeats the purpose of using CORS, right? :) That’s leaving the app open to any request that comes in so it’s almost like not having CORS at all…

    • Yes. But when we work with API servers we need to choose between ‘*’ (aka no restrictions) or a permission nightmare. We also can decide where allow CORS or not.

      Anyway it’s simmilar than the usage of jsonp to avoid the same domain policy. Give us a security policy and we will hack it :)

  1. Pingback: Playing with HTML5. Building a simple pool of WebWokers | Gonzalo Ayuso | Web Architect

  2. Pingback: Upgrading Android apps outside Google Play Store with angularjs | Gonzalo Ayuso | Web Architect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 989 other followers

%d bloggers like this: