Skip to content

Commit e5585ec

Browse files
committed
fix(binding-http): include CORS headers for 404 responses
Signed-off-by: Pranav-0440 <pranavghorpade61@gmail.com>
1 parent 7bda06d commit e5585ec

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

packages/binding-http/src/http-server.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,13 @@ export default class HttpServer implements ProtocolServer {
103103
}
104104

105105
// No url-rewrite mapping found -> resource not found
106-
res.writeHead(404);
106+
const origin = req.headers["origin"];
107+
if (typeof origin === "string") {
108+
res.setHeader("Access-Control-Allow-Origin", origin);
109+
res.setHeader("Vary", "Origin");
110+
}
111+
112+
res.writeHead(404, { "Content-Type": "text/plain" });
107113
res.end("Not Found");
108114
},
109115
});
@@ -622,6 +628,14 @@ export default class HttpServer implements ProtocolServer {
622628
}
623629

624630
private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse) {
631+
// --- GLOBAL CORS HANDLING ---
632+
const origin = req.headers["origin"];
633+
if (typeof origin === "string") {
634+
res.setHeader("Access-Control-Allow-Origin", origin);
635+
res.setHeader("Vary", "Origin");
636+
}
637+
// -----------------------------
638+
625639
const requestUri = new URL(req.url ?? "", `${this.scheme}://${req.headers.host}`);
626640

627641
debug(

packages/binding-http/test/http-server-cors-test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,4 +249,17 @@ class HttpServerCorsTest {
249249
expect(response.status).to.equal(204); // Action without output returns 204
250250
expect(response.headers.get("Access-Control-Allow-Origin")).to.equal("*");
251251
}
252+
253+
@test async "should include CORS headers on 404 response"() {
254+
const uri = `http://localhost:${this.httpServer.getPort()}/nonexistent-resource`;
255+
256+
const response = await fetch(uri, {
257+
headers: {
258+
Origin: "http://example.com",
259+
},
260+
});
261+
262+
expect(response.status).to.equal(404);
263+
expect(response.headers.get("Access-Control-Allow-Origin")).to.equal("http://example.com");
264+
}
252265
}

0 commit comments

Comments
 (0)