1. 로그인 버튼 클릭 : 서버로 로그인 요청 axios
1.1 axios : fetch대신 확장성 좋은 프론트앤드ㅡ백앤드 통신도구
return axios
.post('http://localhost:4000/login', { loginInfo, checkedKeepLogin })
.then((res) => {
setIsLogin(true);
setUserInfo(res.data);
})
.catch((err) => {
if (err.response.status === 401) {
setErrorMessage('로그인에 실패했습니다.');
}
});
res.cookie('cookieId', userInfo.id, cookieOptions); // Expires 옵션이 없는 Session Cookie
res.redirect('/userinfo');
module.exports = (req, res) => {
const cookieId = req.cookies.cookieId;
const userInfo = { ...USER_DATA.filter((user) => user.id === cookieId)[0] };
if (!cookieId || !userInfo.id) {
res.status(401).send('Not Authorized');
} else {
delete userInfo.password;
res.json(userInfo);
}
};
const logoutHandler = () => {
return axios
.post('http://localhost:4000/logout')
.then((res) => {
setUserInfo(null);
setIsLogin(false);
})
.catch((err) => {
alert(err);
});
};
let result = {
accessToken: sign(payload, process.env.ACCESS_SECRET, {
expiresIn: '1d', // 1일간 유효한 토큰을 발행합니다.
}),
};
return result;
const refreshToken = req.cookies['refresh_jwt'];
if (refreshToken) {
res.clearCookie('refresh_jwt', {
domain: 'localhost',
path: '/',
sameSite: 'none',
secure: true,
});
}
if (refreshToken) {
res.cookie('refresh_jwt', refreshToken, {
domain: 'localhost',
path: '/',
sameSite: 'none',
httpOnly: true,
secure: true,
expires: new Date(Date.now() + 24 * 3600 * 1000 * 7), // 7일 후 소멸되는 Persistent Cookie
});
}
const loginRequestHandler = () => {
return window.location.assign(
`https://github.com/login/oauth/authorize?client_id=${CLIENT_ID}`
);
};
const getAccessToken = async (authorizationCode) => {
try {
const result = await axios.post('http://localhost:4000/callback', {
authorizationCode,
});
const { accessToken } = result.data;
setIsLogin(true);
setAccessToken(accessToken);
} catch (err) {
alert(err);
}
};
useEffect(() => {
axios
.post('https://localhost:4000/userinfo', { accessToken })
.then((res) => {
setIsLoading(true) //loading indicator 켜고 시작
const {githubUserData, serverResource} = res.data;
setGithubUser(githubUserData)
setServerResource(serverResource)
setIsLoading(false) //loading indicator 종료
})
.catch((err) => console.log(err))
}, []);