In this blog we will see what is CORS or Cross Origin Resource Sharing and how to handle this issue while developing a mobile app
Introduction
CORS or Cross Origin Resource Sharing is a W3C spec which allows cross domain communication. Lets see what does this mean. Suppose you have a website on http://my-site.com and you want to fire an ajax request to http://api.my-site.com, you browser will not allow this request to get completed. You will see an error like this on console
[code]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.my-site.com. This can be fixed by moving the resource to the same domain or enabling CORS.
[/code]
What this means is browser will block any cross-domain request which you make. Cross Domain requests include
-
Request to a different sub domain (http://a.my-site.com to http://b.my-site.com or even http://my-site.com to http://www.my-site.com)
-
Request to a different website or ip address (http://my-site.com to http://my-site2.com or http://my-site.com to http://144.144.2.2)
-
Request from a http:// site to a https:// site or visa verse (http://my-site.com to https://my-site.com)
This is a basically a security feature built into browser which prevents cross domain requests. To overcome this feature, i.e allow access to the other domain you need to enable CORS.
This is a very common case when your testing your mobile app on your desktop, you mobile application usually run on “localhost” and you api’s are located on server on a different domain or ip address.
How To Enable CORS
To enable CORS, you need to have access to the other domain. So if you want to send a ajax request to lets http://b-mysite.com you need to add some response headers to the request. To do this you add the following headers to response
Access-Control-Allow-Origin : * Access-Control-Allow-Headers : "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With" Access-Control-Allow-Methods : "GET, PUT, POST"
In Express.Js this is done using
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
if ('OPTIONS' === req.method) {
res.status(204).send();
}
else {
next();
}
});
Or use this library https://github.com/troygoode/node-cors
In PHP
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With');
header('Access-Control-Allow-Methods: GET, PUT, POST');
Also CORS is only supported in modern browsers:
Chrome 3+
Firefox 3.5+
Opera 12+
Safari 4+
Internet Explorer 8+