Tuesday, April 24, 2012

Implementing HTML5 CORS on the server.

Hi all, I am here once again with some small hack for you all.

You, as a web developer, might have sometime come across a point where you might have needed to fetch some resources from a server with a different domain name as that of others.

You might have resorted to implementing proxy or resorted to a hack called JSONP.

Now, theres no need to take all that hassel, The goodness of Html5 has brought to you something called CORS(Cross Origin Resource Sharing.)

    But there is 1 downside to CORS
1. You need to have control over the server, but thats not a big deal, you need to have JSONP enabled on server either when using JSONP, same for proxy, you have to have something on server.

thats ok for now, I have seen many people who work with multiple domains and all of them have been under their own ownership. Like we have at my workplace.

ok, getting back to CORS now, heres what you need to implement on the server side, in order to get it working.

a simple header  in your HTTP Response.

                        "Content-Type": "text/plain",
                        "Access-Control-Allow-Origin": "*" //CORS implementation.

Putting '*' as the value of the header will allow any origin to make a call to your domain from withing a CORS supporting browser. If you want to restrict the domains which can make a CORS call, separate them by comma, like this.

                        "Content-Type": "text/plain",
                        "Access-Control-Allow-Origin": "bar.com, foo.com" //CORS implementation.

This is the example where I have implemented CORS when I was playing with my api on Nodester.com, which might be disfunctional at this time, coz I have built it just as a part of play, nothing else.

I hope that you have got an idea now.

in case of any quesiton or comment or criticism, feel free to write down below.

UPDATE: Some more sample code on Github

Thanks & Cheers,
Have fun.

1 comment:

  1. We're a group of volunteers and opening a new scheme in our community. Your site offered us with valuable information to work on. You have done a formidable job and our entire community will be grateful to you.

    Feel free to surf to my page :: aire acondicionado



Related Posts Plugin for WordPress, Blogger...

Share This

Share |