로그인 문제
784
작성한 질문수 19
로그인 테스트 해보려는데 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로 감싸주어서 해결하였습니다.
답변 2
캡처링부분 질문있습니다.
0
76
2
깃에 소스코드를 찾을 수 없습니다.
0
113
2
useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩
0
98
1
import 파일 경로를 찾지 못 해서 에러가 발생합니다.
0
111
2
css 라이브러리 추천 부탁드립니다
0
141
2
팔로우 추천 목록이 빈 배열로 들어옵니다.
0
133
1
게시물 업로드 시 userId가 undefined로 들어가는 오류
0
119
1
useSuspenseQuery 사용 시 SSR 401 이슈 관련
0
172
1
리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??
0
184
3
폴링이 필요없는 이유
0
93
2
next Request Memoization과 react cache
0
110
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
132
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
85
2





