diff --git a/api/echos.ts b/api/echos.ts index e172713..05fac68 100644 --- a/api/echos.ts +++ b/api/echos.ts @@ -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 }); + } +); diff --git a/src/middleware/cors.ts b/src/middleware/cors.ts new file mode 100644 index 0000000..6e5cc90 --- /dev/null +++ b/src/middleware/cors.ts @@ -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 };