Skip to content
Open
Show file tree
Hide file tree
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
16 changes: 15 additions & 1 deletion packages/binding-http/src/http-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,13 @@ export default class HttpServer implements ProtocolServer {
}

// No url-rewrite mapping found -> resource not found
res.writeHead(404);
const origin = req.headers["origin"];
if (typeof origin === "string") {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
}

res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
},
});
Expand Down Expand Up @@ -622,6 +628,14 @@ export default class HttpServer implements ProtocolServer {
}

private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse) {
// --- GLOBAL CORS HANDLING ---
const origin = req.headers["origin"];
if (typeof origin === "string") {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
}
// -----------------------------

const requestUri = new URL(req.url ?? "", `${this.scheme}://${req.headers.host}`);

debug(
Expand Down
13 changes: 13 additions & 0 deletions packages/binding-http/test/http-server-cors-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,17 @@ class HttpServerCorsTest {
expect(response.status).to.equal(204); // Action without output returns 204
expect(response.headers.get("Access-Control-Allow-Origin")).to.equal("*");
}

@test async "should include CORS headers on 404 response"() {
const uri = `http://localhost:${this.httpServer.getPort()}/nonexistent-resource`;

const response = await fetch(uri, {
headers: {
Origin: "http://example.com",
},
});

expect(response.status).to.equal(404);
expect(response.headers.get("Access-Control-Allow-Origin")).to.equal("http://example.com");
}
}