[Cppcms-users] Same origin policy and JSON-RPC
Brought to you by:
artyom-beilis
From: Artyom B. <art...@ya...> - 2011-09-10 08:25:01
|
Hello, Due to the other discussion about json-rpc and same origin policy restriction of XMLHttpRequest I've searched how to apply CORS (Cross Origin Resource Sharing, see [1],[2]) with CppCMS. It was quite simple. I've added this code to the json_rpc/rpc.cpp example (class json_service) virtual void main(std::string url) { // Handle CORS response().set_header("Access-Control-Allow-Origin","*"); response().set_header("Access-Control-Allow-Headers","Content-Type"); if(request().request_method()=="OPTIONS") { return; } cppcms::rpc::json_rpc_server::main(url); } It allows to send appropriate headers and handle JSON-RPC (actually any XMLHttpRequest) in cross domain way. Latest specification of XMLHttpRequest allow to execute cross domain requests if the peer responds on OPTIONS request and sets appropriate headers actually allowing explicitly cross origin request. Few notes: - It requires up to date browsers: Firefox >= 3.5, IE >= 8 and AFAIK any version of Chrome and Safari >= 4 - It currently does not work with internal HTTP web server as it rejects OPTIONS request that was not exist in HTTP/1.0 So you need to run CppCMS behind real web server like Apache, Lighttpd or Nginx. This is fixed in trunk version of CppCMS. Bottom Line: ------------- If you target recent browsers i.e. IE>=8 and FF>=3.5 you don't need to deploy JSONP like techniques. References: [1] http://www.w3.org/TR/cors/ [2] http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing Artyom Beilis |