프로그래밍/NextJS
nextjs api폴더 리팩토링
타코코딩
2024. 1. 6. 02:27
// pages/api/login
import client from "@/app/libs/server/client";
import withHandler from "@/app/libs/server/withHandler";
async function handler(req, res) {
console.log(req.body);
return res.status(200).end();
}
export default withHandler("POST", handler);

// libs/server/withhanlder.js
export default function withHandler(method, fn) {
return async function (req, res) {
if (req.method !== method) {
return res.status(405).end();
}
try {
await fn(req, res);
} catch (error) {
console.log(error);
return res.status(500).json({ error });
}
};
}