inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

173만명의 커뮤니티!! 함께 토론해봐요.

MSW오류 및 서버 액션에 대한 질문입니다!

해결됨

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

안녕하세요!‘서버 컴포넌트에서 Server Actions 사용하기’ 섹션을 듣고 질문 2개가 생겼습니다. 강의를 다 듣고 실제로 진행해보니 저의 경우는 redirect('/home') 으로리다이렉션이 진행되지 않습니다 network탭을 보니 애초에 서버로 데이터 전송이 안 된 것 같습니다 (payload에는 제대로 데이터가 전송이 됐고 Headers를 보면 status가 200이 뜨긴 하네요) 그래서 MSW문제인가 싶어서 http://localhost:9090/ 에 접속해보니 에러가 발생하네요 MSW설정 자체가 문제인것 같은데 강의내용을 보고 그대로 따라했는데 어느 부분에서 문제가 발생한지 도저히 모르겠습니다.. 제 코드들을 첨부하겠습니다 // browser.ts import { setupWorker } from 'msw/browser'; import { handlers } from './handlers'; // This configures a Service Worker with the given request handlers. const worker = setupWorker(...handlers); export default worker; // handlers.ts import { http, HttpResponse } from 'msw'; export const handlers = [ http.post(`/api/login`, () => { console.log('로그인'); return HttpResponse.json( { userId: 1, nickname: '제로초', id: 'zerocho', image: '/5Udwvqim.jpg', }, { headers: { 'Set-Cookie': 'connect.sid=msw-cookie;HttpOnly;Path=/', }, }, ); }), http.post(`/api/logout`, () => { console.log('로그아웃'); return new HttpResponse(null, { headers: { 'Set-Cookie': 'connect.sid=;HttpOnly;Path=/;Max-Age=0', }, }); }), http.post('/api/users', async ({ request }) => { console.log('회원가입'); // 403에러 전용 // return HttpResponse.text(JSON.stringify('user_exists'), { // status: 403, // }); // 성공 전용 return HttpResponse.text(JSON.stringify('ok'), { headers: { 'Set-Cookie': 'connect.sid=msw-cookie;HttpOnly;Path=/;Max-Age=0', }, }); }), ]; // http.ts import { createMiddleware } from '@mswjs/http-middleware'; import express from 'express'; import cors from 'cors'; 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 running on port: ${port}`)); 정확히 서버액션 이라는 개념이 이해가 가질 않습니다 기존 리액트에서 클릭 이벤트 또는 서브밋 이벤트로 폼을 제출하는 방식이 아니라, 폼의 action을 사용해 서버로 폼의 데이터를 제출하는 것같은데, 이것만 보면 그냥 폼데이터 값으로 백엔드 api를 이용하는거같은데.. .정확한 서버 액션 이라는 그 의미를 잘 모르겠네요… 구글링 해보면 따로 api를 생성할 필요 없이 API를 바로 만들어서사용하는거라고 하는데 여기서는 백엔드 API를 사용하고 있고…혹시 다음 강의에 자세한 설명이 나오는것인가요?너무 헷갈리네요

  • react
  • next.js
  • react-query
  • next-auth
  • msw
kraf 댓글 1 좋아요 0 조회수 1202

로그인 문제

미해결

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

로그인 테스트 해보려는데 try, catch 부분 둘 다 실행되네요?. 리다이렉트가 안되는거 같아요 새로 고침하면 로그인 상태는 됩니다. 리다이렉트 안되는 이유가 무엇일까요? 'use client'; import style from '@/app/(beforeLogin)/_component/login.module.css'; import { ChangeEventHandler, FormEventHandler, useState } from 'react'; import { useRouter } from 'next/navigation'; import { signIn } from 'next-auth/react'; // 클라이언트에서는 next-auth/react에서 임포트 export default function Page() { const [id, setId] = useState(''); const [password, setPassword] = useState(''); const [message, setMessage] = useState(''); const router = useRouter(); const onSubmit: FormEventHandler<HTMLFormElement> = async (e) => { e.preventDefault(); setMessage(''); try { await signIn('credentials', { username: id, password, redirect: false, }); router.replace('/home'); } catch (error) { console.error(error); setMessage('아이디와 비밀번호가 일치하지 않습니다.'); } }; const onClickClose = () => { router.back(); }; const onChangeId: ChangeEventHandler<HTMLInputElement> = (e) => { setId(e.target.value); }; const onChangePassword: ChangeEventHandler<HTMLInputElement> = (e) => { setPassword(e.target.value); }; return ( <div className={style.modalBackground}> <div className={style.modal}> <div className={style.modalHeader}> <button className={style.closeButton} onClick={onClickClose}> <svg width={24} viewBox='0 0 24 24' aria-hidden='true' className='r-18jsvk2 r-4qtqp9 r-yyyyoo r-z80fyv r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-19wmn03' > <g> <path d='M10.59 12L4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12z'></path> </g> </svg> </button> <div>로그인하세요.</div> </div> <form onSubmit={onSubmit}> <div className={style.modalBody}> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor='id'> 아이디 </label> <input id='id' className={style.input} value={id} onChange={onChangeId} type='text' placeholder='' /> </div> <div className={style.inputDiv}> <label className={style.inputLabel} htmlFor='password'> 비밀번호 </label> <input id='password' className={style.input} value={password} onChange={onChangePassword} type='password' placeholder='' /> </div> </div> <div className={style.message}>{message}</div> <div className={style.modalFooter}> <button className={style.actionButton} disabled={!id && !password}> 로그인하기 </button> </div> </form> </div> </div> ); } 핸들러 부분도 수정했습니다. const User = [ { id: 'elonmusk', nickname: 'Elon Musk', image: '/yRsRRjGO.jpg' }, { id: 'zerohch0', nickname: '제로초', image: '/5Udwvqim.jpg' }, { id: 'dongwook98', nickname: '신동마', password: '1234', image: '/me.jpeg' }, { id: 'leoturtle', nickname: '레오', image: faker.image.avatar() }, ]; const Posts = []; export const handlers = [ http.post('/api/login', () => { console.log('로그인'); return HttpResponse.json(User[2], { headers: { 'Set-Cookie': 'connect.sid=msw-cookie;HttpOnly;Path=/', }, }); }), 추가로 콘솔 에러 메시지 입니다. 이걸 보고 AUTH_URL 도 확인해보았는데 다 잘 적어줬습니다. 또 로그인 하기 전 메인 페이지에서 로그인 버튼 눌러서 로그인 모달이 뜨는 순간 콘솔 탭에 이러한 에러 메시지가 생깁니다. 위 에러 메시지는 검색해서 useEffect(() => { router.replace('/i/flow/login'); }, []); useEffect로 감싸주어서 해결하였습니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
욱둥이 댓글 1 좋아요 1 조회수 804

페러렐과 인터셉트 라우팅을 활용한 모달에 대한 질문입니다.

해결됨

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

기존의 모달 방식(제 기준) 은 Context나 recoil과 같은 상태관리 모달로 Provider를 만들어서 isOpen setIsOpen과 같이 사용했는데 이번에 배운 방식도 좋은 방법인 것 같지만, 폴더 구조가 엉망이 되서 가독성이 떨어지는 것 같다는 생각이 들어서 강사님 생각에는 어떤 방식이 어느 상황에서 더 좋을 것 같은지 궁금해서 질문 드려 봅니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
리액트 매니아 댓글 1 좋아요 1 조회수 544

github에 올라와 있는 파일중에 module.css파일이 있나요?

해결됨

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

저는 여기서 파일을 zip으로 다운받아서 복사하려고 했는데 https://github.com/ZeroCho/next-app-router-z module.css파일을 찾을 수가 없어서 혹시 어디서 찾아야 할까요?

  • react
  • next.js
  • react-query
  • next-auth
  • msw
리액트 매니아 댓글 1 좋아요 0 조회수 474

타입스크립트 질문

미해결

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

useFormState initialState부분 타입스크립트 에러 질문입니다. message에 string이 와야한다고 에러가 뜨는데 이거를 string | null로 해주는 방법을 잘 모르겠습니다! const initialState: { message: string | null; } = { message: null, }; export default function SignupModal() { const [state, formAction] = useFormState(onSubmit, initialState); const { pending } = useFormStatus(); 일단 이런식으로 빼서 에러 없애긴하였는데 인라인으로는 못하나요?

  • react
  • next.js
  • react-query
  • next-auth
  • msw
욱둥이 댓글 3 좋아요 0 조회수 1163

프론트엔드 세션과 백엔드 세션 / queryClient.getQueryCache에 대한 질문이 있습니다!

해결됨

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

안녕하세요! 제로초님! 항상 강의를 감사히 잘 보고있습니다! 다름이 아니라, 세션에 대한 질문이 있어 글을 올립니다. 첫번째 질문입니다! 현재 클라이언트(브라우저)에서 로그인 요청 시, auth.js를 사용해서 프론트측 세션을 생성하고, 그것을 통해서 클라이언트의 로그인 상태에 대한 분기 기준으로 사용하고 있고, 백엔드에서도 API 허가를 위한 세션을 받아 connect.sid 라는 쿠키를 생성하여 총 2개의 쿠키를 이용하고 있습니다. 제가 궁금한 것은 현재 2개로 나누어진 세션을 백엔드에서 주는 세션으로 생성한 쿠키 1개만 사용해도 되지 않을까? 라는 생각이 들었는데, 각각 따로따로 세션을 생성해서 처리하는 이유가 궁금합니다. 혹시 프론트엔드 입장에서 next-auth (auth.js)가 제공해주는 기능(CSRF, useSession, signin 등의 메서드... )들이 편리해서, 이것을 사용하신것이고 강의에서 언급하신대로 백엔드 세션과 통합하는 과정이 아직 불완전하여 따로 둔 상태로 둔 것이며, 만약 next-auth가 주는 장점이 굳이 없었다면 처음부터 백엔드 세션 1개를 이용해서 로그인 과정을 구현했을 것 이다. 라고 제가 감히 예상을 해도 될까요.. ? 🤔 두번째 질문입니다. [재게시, 답글기능 zustand로 만들어보기] 강의 17분 40초 부근에서 queryClient.getQueryData 보다 getQueryCache를 사용하는게 더 정확하다라고 말씀하셨는데 그 이유가 궁금합니다!

  • react
  • next.js
  • react-query
  • next-auth
  • msw
withkey 댓글 1 좋아요 1 조회수 703

패러랠 라우트 질문(로그인 모달 관련)

해결됨

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

로그인모달을 패러랠 라우트 방식으로 구현하는 과정에서 default.tsx 강의 타임라인 0:34에서 app/(beforeLogin)/@modal 폴더에 있던 page.tsx와 login.module.css파일을 복사해서 app/(beforeLogin)/i/flow/login로 디렉터리를 만들어서 거기에다가 page.tsx와 login.module.css파일로 넣으셨는데요. URL이 http://localhost:3000/i/flow/login이면 @modal 하위에도 그 url 경로대로 폴더 구조를 맞춰서 넣어줘야 하는 것이죠? 패러랠방식에 대해서 아직 감이 안잡힙니다. (beforeLogin)폴더 자식으로 @modal폴더와 layout.tsx에 가 있고 laytout.tsx에서 modal을 props로 가져옵니다. 그럼 그 modal이라고 이름지은 것은 같은 뎁스에 있는 "@자기이름"인 @modal을 탐색해서 가져오는건가요? import { ReactNode } from "react"; import styles from "@/app/page.module.css"; type Props = { children: ReactNode; modal: ReactNode; }; export default async function BeforeLoginLayout({ children, modal }: Props) { return ( <div> <div className={styles.container}> {children} {modal} </div> </div> ); }

  • react
  • next.js
  • react-query
  • next-auth
  • msw
gga01075 댓글 1 좋아요 2 조회수 915

인터셉팅 라우트 버그?..

미해결

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

게시하기 버튼 클릭하면 인터셉팅 라우트가 되지 않네요 ㅜ 회원가입, 로그인에서는 인터셉팅 라우트가 잘 됬었는데 왜이러는걸까요?.. 아직 넥스트가 불안정 한건지.. 검색해도 잘 안나오네요..

  • react
  • next.js
  • react-query
  • next-auth
  • msw
욱둥이 댓글 1 좋아요 0 조회수 671

google font fetchError 가 나는데요...

미해결

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

섹션1까지 들은 수강생입니다 🙂 프로젝트 실행시 아래와같은 에러가 나오는데요.. 어떻게 해결해야할지 ㅠㅠ FetchError: request to https://fonts.gstatic.com/s/inter/v13/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa2pL7W0Q5n-wU.woff2 failed, reason: self-signed certificate in certificate chain at ClientRequest.<anonymous> (C:\simjieun\study\next.js\twitter_clone_nextjs\node_modules\next\dist\compiled\node-fetch\index.js:1:65756) at ClientRequest.emit (node:events:514:28) at TLSSocket.socketErrorListener (node:_http_client:501:9) at TLSSocket.emit (node:events:514:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { type: 'system', errno: 'SELF_SIGNED_CERT_IN_CHAIN', code: 'SELF_SIGNED_CERT_IN_CHAIN' } ⨯ Failed to download `Inter` from Google Fonts. Using fallback font instead. Failed to fetch `Inter` from Google Fonts.} FetchError: request to https://fonts.gstatic.com/s/inter/v13/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa1pL7W0Q5n-wU.woff2 failed, reason: self-signed certificate in certificate chain at ClientRequest.<anonymous> (C:\simjieun\study\next.js\twitter_clone_nextjs\node_modules\next\dist\compiled\node-fetch\index.js:1:65756) at ClientRequest.emit (node:events:514:28) at TLSSocket.socketErrorListener (node:_http_client:501:9) at TLSSocket.emit (node:events:514:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { type: 'system', errno: 'SELF_SIGNED_CERT_IN_CHAIN', code: 'SELF_SIGNED_CERT_IN_CHAIN' } ....

  • react
  • next.js
  • react-query
  • next-auth
  • msw
simjieun 댓글 1 좋아요 0 조회수 1096

nextjs 버전

해결됨

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

'Next프로젝트 시작하기' 6:50 초에 현재는 npx create-next-app@latest 명령시 14버전이 설치되는데 상관이 없는건가요?

  • react
  • next.js
  • react-query
  • next-auth
  • msw
gga01075 댓글 1 좋아요 2 조회수 712

vanila-extract window 문제

해결됨

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

windows 에서 vanila-extract 의 문제점은 구체적으로 어떤 것일까요? https://github.com/vanilla-extract-css/vanilla-extract/issues/1086 해당 이슈가 맞는지 궁금합니다!

  • react
  • next.js
  • react-query
  • next-auth
  • msw
부드러운 펭귄 댓글 1 좋아요 0 조회수 1048

MSW 질문입니다

미해결

따라하며 배우는 리액트 테스트 [2023.11 업데이트]

MSW를 사용해 구현하는것이 json-server를 사용하는 것과 비교했을때 갖는 이점이 어떤게 있나요? end to end 테스트를 하지 않고 중간에서 서비스워커가 백그라운드에서 실행하는 형태 라는 이점이 있는건가요? '그렇다면 리소스 낭비를 하지 않는다' 라는 이점이 있는걸까요?

  • msw
  • react
  • React-Context
  • 웹앱
  • jest
jeus0630 댓글 0 좋아요 0 조회수 256

인기 태그

인프런 TOP Writers

주간 인기글