Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CORS support - fixes #501 #507

Merged
merged 1 commit into from
Jun 29, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions source/app.d
Original file line number Diff line number Diff line change
@@ -165,7 +165,26 @@ shared static this()
auto urlRouter = new URLRouter;
auto fsettings = new HTTPFileServerSettings;
fsettings.serverPathPrefix = "/static";

void cors(HTTPServerRequest req, HTTPServerResponse res)
{
import std.algorithm: among, equal, until;
if (req.host.until(":").among!equal("tour.dlang.org", "tour.dlang.io", "dlang.org", "dtest.dlang.io", "127.0.0.1", "localhost"))
{
res.headers["Access-Control-Allow-Origin"] = "*";
}
// parse json sent via text/plain to avoid an additional preflight OPTIONS request
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
if (req.contentType == "text/plain")
{
req.contentType = "application/json; charset=UTF-8";
auto bodyStr = req.bodyReader.readAllUTF8;
if (!bodyStr.empty) req.json = parseJson(bodyStr);
}
}

urlRouter
.any("/api/*", &cors)
.registerWebInterface(new WebInterface(contentProvider, config.googleAnalyticsId, defaultLang))
.registerRestInterface(new ApiV1(execProvider, contentProvider))
.get("/static/*", serveStaticFiles(publicDir.buildPath("static"), fsettings));