On Mon, 03 Feb 2014 08:44:58 GMT, Sönke Ludwig wrote:
On Sun, 26 Jan 2014 17:57:01 GMT, Marenz wrote:
Hello,
I am building a small server with an API to receive & return json objects through http POST/GET.
From js, I tried calling my server using
$.ajax({ url: "http://my.domain:8989/register", type: "POST", crossDomain: true, data: { apiKey: "23462", method: "example", ip: "208.74.35.5" }, success: function (result) { resultDiv.innerHTML=result; }, error: function (xhr, ajaxOptions, thrownError) { } });
Which gives the error:
XMLHttpRequest cannot load http://my.domain:8989/register. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
On the server I see something like
IP - - 2014-Jan-26 17:56:15.0144105Z "OPTIONS /register HTTP/1.1" 404 455 "http://localhost/supraball/serverlist.html" "uagent"
So there is an OPTION request to which it response with 404.
How can I respond to OPTION requests and/or how can I add the required header "Access-Control-Allow-Origin"?The most simple way to solve this would be to explicitly add a route for this in the
URLRouter
:void sendOptions(HTTPServerRequest req, HTTPServerResponse res) { res.headers["Access-Control-Allow-Origin"] = "*"; res.writeBody(""); } auto router = new URLRouter; router.match(HTTPMethod.options, "/register", &sendOptions); // ...
Plus probably the header should also be sent with every other response:
void addACAO(HTTPServerRequest req, HTTPServerResponse res) { res.headers["Access-Control-Allow-Origin"] = "*"; } void sendOptions(HTTPServerRequest req, HTTPServerResponse res) { addACAO(req, res); res.writeBody(""); } auto router = new URLRouter; router.any("*", &addACAO); router.match(HTTPMethod.options, "*", &sendOptions); // ...
The
"*"
for the header value should also probably be something more specific for the application.Currently there is not really a sane way to implement this directly in vibe.d. But later, when the high level web framework in
vibe.web
gets some more features, that would be a good place to add something like this by default.