Skip to content

Commit

Permalink
fix: cors
Browse files Browse the repository at this point in the history
  • Loading branch information
srph committed Nov 28, 2024
1 parent 9195e2d commit 5cb71df
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
9 changes: 6 additions & 3 deletions api/echos.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { VercelRequest, VercelResponse } from "@vercel/node";
import { echos } from "../src/echos";
import { cors } from "../src/middleware/cors";

export default function (_request: VercelRequest, response: VercelResponse) {
response.json({ echos });
}
export default cors(
async (_request: VercelRequest, response: VercelResponse) => {
response.json({ echos });
}
);
31 changes: 31 additions & 0 deletions src/middleware/cors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type {
VercelRequest,
VercelResponse,
VercelApiHandler,
} from "@vercel/node";

const cors =
(fn: VercelApiHandler) => async (req: VercelRequest, res: VercelResponse) => {
res.setHeader("Access-Control-Allow-Credentials", "true");

res.setHeader("Access-Control-Allow-Origin", "*");

res.setHeader(
"Access-Control-Allow-Methods",
"GET,OPTIONS,PATCH,DELETE,POST,PUT"
);

res.setHeader(
"Access-Control-Allow-Headers",
"X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
);

if (req.method === "OPTIONS") {
res.status(200).end();
return;
}

return await fn(req, res);
};

export { cors };

0 comments on commit 5cb71df

Please sign in to comment.