작성
·
674
0
// http.ts
import { createMiddleware } from "@mswjs/http-middleware";
import cors from "cors";
import express from "express";
import { handlers } from "./handlers";
const app = express();
const port = 9090;
app.use(
cors({
origin: "http://localhost:3000",
optionsSuccessStatus: 200,
credentials: true,
})
);
app.use(express.json());
app.use(createMiddleware(...handlers));
app.listen(port, () => console.log(`Mock server is ruuning on port: ${port}`));
// handlers.ts
import { http, HttpResponse } from "msw";
const CalendarData = [
{
id: 0,
date: "2024-03-01",
memo: [
{
id: 0,
text: "식사",
},
{
id: 1,
text: "운동",
},
],
},
{
id: 1,
date: "2024-03-02",
memo: [
{
id: 0,
text: "연차",
},
{
id: 1,
text: "회의",
},
],
},
{
id: 2,
date: "2024-03-03",
reservation: 0,
canceled: 0,
noShow: 0,
memo: [],
},
{
id: 3,
date: "2024-03-04",
memo: [
{
id: 0,
text: "공부",
},
{
id: 1,
text: "휴식",
},
],
},
{
id: 4,
date: "2024-03-05",
memo: [],
},
{
id: 30,
date: "2024-03-31",
memo: [
{
id: 0,
text: "파티",
},
{
id: 1,
text: "운동",
},
],
},
];
export const handlers = [
http.get("http://localhost:3000/api/calendar", ({}) => {
return HttpResponse.json(CalendarData);
}),
];
// browser.ts
import { setupWorker } from "msw/browser";
import { handlers } from "./handlers";
const worker = setupWorker(...handlers);
export default worker;
// MSWComponent.tsx
"use client";
import { useEffect } from "react";
export const MSWComponent = () => {
useEffect(() => {
if (typeof window !== "undefined") {
if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") {
require("@/mocks/browser");
}
}
}, []);
return null;
};
// msw api 요청 함수
export async function getCalendarData() {
const res = await fetch(`http://localhost:3000/api/calendar`, {
next: {
tags: ["calendar"],
},
cache: "no-store",
});
if (!res.ok) {
throw new Error("Failed to fetch calendar data");
}
return res.json();
}
// layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import PortalWrap from "@/components/PortalWrap/PortalWrap";
import Toast from "@/components/Toast/Toast";
import { MSWComponent } from "@/mocks/MSWComponent";
import SSRQueryClientProvider from "@/libs/ReactQuery/SSRQueryClientProvider";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<MSWComponent />
<SSRQueryClientProvider>
{children}
<PortalWrap />
<Toast />
</SSRQueryClientProvider>
</body>
</html>
);
}
// .env
NEXT_PUBLIC_API_MOCKING=enabled
NEXT_PUBLIC_MODE=local
// package.json
{
"name": "planner",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"mock": "npx tsx watch ./src/mocks/http.ts"
},
"dependencies": {
"@tanstack/react-query": "^5.14.6",
"classnames": "^2.5.1",
"date-fns": "^3.3.1",
"next": "^14.0.3",
"react": "^18",
"react-dom": "^18",
"react-icons": "^5.0.1",
"react-transition-group": "^4.4.5",
"sass": "^1.71.1",
"zustand": "^4.5.2"
},
"devDependencies": {
"@mswjs/http-middleware": "^0.9.2",
"@tanstack/react-query-devtools": "^5.25.0",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^20.10.5",
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/react-transition-group": "^4.4.10",
"autoprefixer": "^10.0.1",
"cors": "^2.8.5",
"eslint": "^8",
"eslint-config-next": "14.1.2",
"express": "^4.18.2",
"msw": "^2.0.11",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"typescript": "^5"
},
"msw": {
"workerDirectory": "public"
}
}
npm run mock
를 사용해서 터미널에 Mock server is ruuning on port: 9090
이 나오는것까지 확인되었는데 GET http://localhost:3000/api/calendar 404 (Not Found)
콘솔에 이렇게 오류가 나옵니다.
몇시간 동안 이것저것 수정해보고 했는데 어디서 잘못된건지 왜 요청을 못받아오는지 모르겠습니다ㅠ
답변 1
0
export const handlers = [
http.get("/api/calendar", ({}) => {
return HttpResponse.json(CalendarData);
}),
];
msw에는 호스트를 적는 게 아닙니다. 그리고 fetch 요청도 localhost:9090으로 하셔야 합니다.
아 헐..기존에 BASE_URL로 작성해놓앗어서..3000에 요청하고잇엇는줄 알앗네요
조금만 생각했어도 바로 해결가능했을텐데;;;죄송합니다 ㅠ