• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

MSW 오류가 발생해서 도움 부탁드립니다

24.02.05 15:58 작성 조회수 263

0

서버 컴포넌트에서 Server Actions 사용하기 강의까지 그대로 따라하고 오류때문에 다시 반복해봐도 오류가 발생해서 코드 남깁니다.

<SignupModal.tsx>

import style from "./signup.module.css";
import { redirect, useRouter } from "next/navigation";
import { ChangeEventHandler, FormEventHandler, useState } from "react";
import BackButton from "./BackButton";

export default function SignupModal() {
  const submit = async (formData: FormData) => {
    "use server";
    if (!formData.get("id")) {
      return { message: "no_id" };
    }
    if (!formData.get("name")) {
      return { message: "no_name" };
    }
    if (!formData.get("password")) {
      return { message: "no_password" };
    }
    if (!formData.get("image")) {
      return { message: "no_image" };
    }
    let shouldRedirect = false;
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_BASE_URL}/api/users`,
        {
          method: "post",
          body: formData,
          credentials: "include", //쿠키를 사용하여 로그인 여부를 파악하기 위함
        }
      );
      console.log(response.status);
      // if (response.status === 403) {
      //   return { message: "user_exists" };
      // } // 이미 유저가 존재할때 403 보내주기로 약속
      console.log(await response.json());
      shouldRedirect = true;
    } catch (err) {
      console.log(err);
    }
    if (shouldRedirect) {
      redirect("/home"); //try/catch문 안에 있으면 안됨.
    }
  };

  return (
    <>
      <div className={style.modalBackground}>
        <div className={style.modal}>
          <div className={style.modalHeader}>
            <BackButton />
            <div>계정을 생성하세요.</div>
          </div>
          <form action={submit}>
            <div className={style.modalBody}>
              <div className={style.inputDiv}>
                <label className={style.inputLabel} htmlFor="id">
                  아이디
                </label>
                <input
                  id="id"
                  name="id"
                  className={style.input}
                  type="text"
                  placeholder=""
                  required
                />
              </div>
              <div className={style.inputDiv}>
                <label className={style.inputLabel} htmlFor="name">
                  닉네임
                </label>
                <input
                  id="name"
                  name="name"
                  className={style.input}
                  type="text"
                  placeholder=""
                  required
                />
              </div>
              <div className={style.inputDiv}>
                <label className={style.inputLabel} htmlFor="password">
                  비밀번호
                </label>
                <input
                  id="password"
                  name="password"
                  className={style.input}
                  type="password"
                  placeholder=""
                  required
                />
              </div>
              <div className={style.inputDiv}>
                <label className={style.inputLabel} htmlFor="image">
                  프로필
                </label>
                <input
                  id="image"
                  name="image"
                  className={style.input}
                  type="file"
                  accept="image/*"
                  required
                />
              </div>
            </div>
            <div className={style.modalFooter}>
              <button type="submit" className={style.actionButton}>
                가입하기
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
}

>

<handlers.ts>

http.post("/api/users", async ({ request }) => {
    console.log("회원가입");
    // return HttpResponse.text(JSON.stringify('user_exists'), {
    //   status: 403,
    // })
    return HttpResponse.text(JSON.stringify("ok"), {
      headers: {
        "Set-Cookie": "connect.sid=msw-cookie;HttpOnly;Path=/",
      },
    });
  }),

>

이런식으로 강의와 똑같이 작성했고, 질문글중 회원가입 코드에 Path부분 빼라고 해보셔서 해봤는데 안됩니다.
실행하고, 가입하기 버튼을 눌렀을때 redirect가 안되고, 헤더 200, 페이로드는 뜨지만 미리보기, 응답이 뜨지 않습니다.
그리고 에러코드에
TypeError: fetch failed
<cause: Error: getaddrinfo ENOTFOUND loalhost

at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:118:26)

at GetAddrInfoReqWrap.callbackTrampoline (node:internal/async_hooks:130:17) {

errno: -3008,

code: 'ENOTFOUND',

syscall: 'getaddrinfo',

hostname: 'loalhost'

}

}>

이런 에러가 떠서 검색도 해봤지만 해결이 안되서 질문 드립니다.

답변 1

답변을 작성해보세요.

0

loalhost 오타입니다. (에러메시지에 나와있습니다)