inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

Next + React Query로 SNS 서비스 만들기

안녕하세요 복습중인데 msw 404 (Not Found) 질문드립니다.

894

밍끼

작성한 질문수 9

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) 콘솔에 이렇게 오류가 나옵니다.
몇시간 동안 이것저것 수정해보고 했는데 어디서 잘못된건지 왜 요청을 못받아오는지 모르겠습니다ㅠ

react next.js react-query next-auth msw

답변 1

0

제로초(조현영)

export const handlers = [
  http.get("/api/calendar", ({}) => {
    return HttpResponse.json(CalendarData);
  }),
];

msw에는 호스트를 적는 게 아닙니다. 그리고 fetch 요청도 localhost:9090으로 하셔야 합니다.

0

밍끼

아 헐..기존에 BASE_URL로 작성해놓앗어서..3000에 요청하고잇엇는줄 알앗네요
조금만 생각했어도 바로 해결가능했을텐데;;;죄송합니다 ㅠ

0

제로초(조현영)

죄송하실것 까지야.. ㅎㅎㅎㅎ

캡처링부분 질문있습니다.

0

74

2

깃에 소스코드를 찾을 수 없습니다.

0

113

2

useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩

0

98

1

import 파일 경로를 찾지 못 해서 에러가 발생합니다.

0

109

2

css 라이브러리 추천 부탁드립니다

0

140

2

팔로우 추천 목록이 빈 배열로 들어옵니다.

0

130

1

게시물 업로드 시 userId가 undefined로 들어가는 오류

0

119

1

useSuspenseQuery 사용 시 SSR 401 이슈 관련

0

171

1

리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??

0

184

3

폴링이 필요없는 이유

0

93

2

next Request Memoization과 react cache

0

108

2

seo 최적화 기준은 데이터 fetching인가요 아님 데이터 렌더링인가요?

0

84

2

next.js 서버fetch 에러 fallback ui 구현 방법

0

173

2

프레임워크 여론 파악법

0

125

2

필터옵션이 많은 페이지에서 서버 fetch를 하는게 맞는걸까요??

0

103

2

서버 fetch suspense 로 감싸고 새로고침 시 잠시 빈 화면이 노출된 후 fallback ui가 노출됩니다.

0

102

2

template.tsx 내 서버fetch 응답값과 클라이언트 컴포넌트 상태값 싱크가 맞지 않는 이슈

0

66

2

Auth.js 사용 시 authorize 함수가 호출되지 않습니다

0

131

2

next.js 에서 로그인에 관하여

0

138

1

Next의 route handler에 대한 질문이 있습니다.

0

101

2

게시판 리스트 만들때 use client를 어디서부터 집어넣어야할지 모르겠습니다

0

98

2

프라이빗 폴더를 해야 하는 이유가 모호한 것 같아요.

0

85

2

vanilla-extract 못찾는 문제

0

230

2

fetch 캐싱과 revalidate 관련

0

84

2