Skip to content

Commit 6adf872

Browse files
committed
fix: return CORS headers with non-OPTIONS responses
1 parent 0c83fe6 commit 6adf872

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

src/index.ts

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,6 @@ const rvs = new NodeCache({
4949
useClones: false,
5050
});
5151

52-
app.options("/", cors({
53-
origin: "*",
54-
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
55-
allowedHeaders: ["X-Requested-With", "Content-Type", "Authorization"], // https://spec.matrix.org/v1.10/client-server-api/#web-browser-clients
56-
exposedHeaders: ["ETag"],
57-
}));
58-
5952
function notFound(res: express.Response): express.Response {
6053
return res.status(404).json({ "errcode": "M_NOT_FOUND", "error": "Rendezvous not found" });
6154
}
@@ -74,7 +67,16 @@ function withContentType(req: express.Request, res: express.Response) {
7467
return fn(contentType);
7568
};
7669
}
77-
app.post("/", (req, res) => {
70+
71+
const postCors = cors({
72+
origin: "*",
73+
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
74+
allowedHeaders: ["X-Requested-With", "Content-Type", "Authorization"], // https://spec.matrix.org/v1.10/client-server-api/#web-browser-clients
75+
exposedHeaders: ["ETag"],
76+
});
77+
78+
app.options("/", postCors);
79+
app.post("/", postCors, (req, res) => {
7880
withContentType(req, res)((contentType) => {
7981

8082
let id: string | undefined;
@@ -92,14 +94,15 @@ app.post("/", (req, res) => {
9294
});
9395
});
9496

95-
app.options("/:id", cors({
97+
const sessionCors = cors({
9698
origin: "*",
9799
methods: ["GET", "PUT", "DELETE", "OPTIONS"],
98100
allowedHeaders: ["If-Match", "If-None-Match"],
99101
exposedHeaders: ["ETag"],
100-
}));
102+
});
101103

102-
app.put("/:id", (req, res) => {
104+
app.options("/:id", sessionCors);
105+
app.put("/:id", sessionCors, (req, res) => {
103106
withContentType(req, res)((contentType) => {
104107
const { id } = req.params;
105108
const rv = rvs.get<Rendezvous>(id);
@@ -128,7 +131,7 @@ app.put("/:id", (req, res) => {
128131
});
129132
});
130133

131-
app.get("/:id", (req, res) => {
134+
app.get("/:id", sessionCors, (req, res) => {
132135
const { id } = req.params;
133136
const rv = rvs.get<Rendezvous>(id);
134137

@@ -150,7 +153,7 @@ app.get("/:id", (req, res) => {
150153
return rv.sendData(res);
151154
});
152155

153-
app.delete("/:id", (req, res) => {
156+
app.delete("/:id", sessionCors, (req, res) => {
154157
const { id } = req.params;
155158
if (!rvs.has(id)) {
156159
return notFound(res);

0 commit comments

Comments
 (0)