-
카테고리
-
세부 분야
풀스택
-
해결 여부
해결됨
로그아웃이 작동하지 않아서 질문드립니다.
23.08.24 15:42 작성 조회수 357
0
안녕하세요 제로초님 로그인은 되는데 로그아웃이 되지않아서 질문남깁니다.
로그인 한 다음 로그아웃을 하면
위와 같이 AxiosError가 나서 네트워크와 리덕스를 확인해보니깐
로그아웃 요청시 302 Found가 뜨고
404 Not Found라는 에러 메세지가 뜹니다.
그리고 리덕스에서는 실패 메세지가 뜹니다.
// UserProfile
import { logoutRequestAction } from '../reducers/user';
const dispatch = useDispatch();
const { me, logOutLoading } = useSelector((state) => state.user);
const onLogOut = useCallback(() => {
dispatch(logoutRequestAction());
}, []);
<Button onClick={onLogOut} loading={logOutLoading}>
로그아웃
</Button>
// 리덕스
logOutLoading: false, // 로그아웃 시도중
logOutDone: false,
logOutError: null,
export const LOG_OUT_REQUEST = 'LOG_OUT_REQUEST';
export const LOG_OUT_SUCCESS = 'LOG_OUT_SUCCESS';
export const LOG_OUT_FAILURE = 'LOG_OUT_FAILURE';
case LOG_OUT_REQUEST:
draft.logOutLoading = true;
draft.logOutDone = false;
draft.logOutError = null;
break;
case LOG_OUT_SUCCESS:
draft.logOutLoading = false;
draft.logOutDone = true;
draft.me = null;
break;
case LOG_OUT_FAILURE:
draft.logOutLoading = false;
draft.logOutError = action.error;
break;
사가
axios.defaults.baseURL = 'http://localhost:3065';
function logOutAPI() {
return axios.post('/user/logout');
}
function* logOut() {
try {
yield call(logOutAPI);
yield put({
type: LOG_OUT_SUCCESS,
});
} catch (err) {
console.log(err);
yield put({
type: LOG_OUT_FAILURE,
error: err.response.data,
});
}
}
function* watchLogOut() {
yield takeEvery(LOG_OUT_REQUEST, logOut);
}
app.js
const express = require('express');
const cors = require('cors');
// session, cookieParser, dotenv
const session = require('express-session');
const cookieParser = require('cookie-parser');
const dotenv = require('dotenv');
// passport 로그인 설정
const passport = require('passport');
const passportConfig = require('./passport');
passportConfig();
const postRouter = require('./routes/post');
const userRouter = require('./routes/user');
dotenv.config();
const app = express();
// 시퀄라이즈 - db 연결
const db = require('./models/index.js');
db.sequelize
.sync()
.then(() => {
console.log('db 연결 성공');
})
.catch(console.error);
app.use(
cors({
origin: true,
credentials: true,
})
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// session,cookieParser
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(
session({
saveUninitialized: false,
resave: false,
secret: process.env.COOKIE_SECRET,
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use('/post', postRouter);
app.use('/user', userRouter);
app.listen(3065, () => {
console.log('3065 포트에서 대기중');
});
user.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const bcrypt = require('bcrypt');
const { User, Post } = require('../models');
// 로그인 POST/user/login
router.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
console.error(err);
return next(err);
}
if (info) {
return res.status(403).send(info.reason);
}
return req.login(user, async (loginErr) => {
if (loginErr) {
console.error(loginErr);
return next(loginErr);
}
const fullUserWithoutPassword = await User.findOne({
where: { id: user.id },
attributes: {
exclude: ['password'],
},
include: [
{
model: Post,
},
{
model: User,
as: 'Followings',
},
{
model: User,
as: 'Followers',
},
],
});
return res.status(200).json(fullUserWithoutPassword);
});
})(req, res, next);
});
// 로그아웃 POST/user/logout
router.post('/logout', (req, res, next) => {
req.logout(() => {
res.redirect('/');
});
});
//회원가입 POST / user
router.post('/', async (req, res, next) => {
try {
const exUser = await User.findOne({
where: {
email: req.body.email,
},
});
if (exUser) {
return res.status(403).send('이미 사용중인 아이디입니다.');
}
const hashedPassword = await bcrypt.hash(req.body.password, 10);
await User.create({
email: req.body.email,
nickname: req.body.nickname,
password: hashedPassword,
});
res.status(200).send('ok');
} catch (error) {
console.error(error);
next(error);
}
});
module.exports = router;
로그인과 회원가입은 제대로 작동하는데 로그아웃만 되지 않습니다.
답변을 작성해보세요.
0
조현영
지식공유자2023.08.24
router.post('/logout', (req, res, next) => { req.logout(() => { res.send('ok'); }); });
해보세요. 지금 backend에서 redirect를 하고 있는데 redirect할 필요가 없습니다.
답변 1