Google 전략을 사용하도록 패스포트를 설정했으며/auth/google로 바로 보낼 수 있습니다. 현재 Google 인증 oauth2를 사용하여 로그인 할 때 나의 엔드 포인트는 req.user
을 확인하여 인증합니다. 이것은 브라우저에서 끝점으로 갈 때 작동합니다. /auth/google
으로 이동 한 다음 /questions
으로 가면 요청할 수 있습니다. 그러나 redux에서 가져 오기 요청을 만들려고하면 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
이라는 오류 메시지가 표시됩니다. 가져 오기 API가 내 /questions
엔드 포인트에 도달하려고 시도하고 내 loggedIn
미들웨어를 통과 한 다음 if (!req.user)
을 충족시키지 못하고 대신 리다이렉션됨에 따라 표시됩니다. PassportJS 및 passport-google-oauth2를 사용하여 Fetch API에서 인증하는 방법에 대한 아이디어가 있습니까?끝점에서 Fetch API 호출로 인증되지 않음 (passport-google-oauth2 사용)
loggedIn
기능 :
function loggedIn(req, res, next) {
if (req.user) {
next();
} else {
res.redirect('/');
}
}
여기 내 'GET'엔드 포인트에 대한 내 코드입니다.
router.get('/', loggedIn, (req, res) => {
const userId = req.user._id;
User.findById(userId, (err, user) => {
if (err) {
return res.status(400).json(err);
}
Question.findById(user.questions[0].questionId, (err, question) => {
if (err) {
return res.status(400).json(err);
}
const resQuestion = {
_id: question._id,
question: question.question,
mValue: user.questions[0].mValue,
score: user.score,
};
return res.status(200).json(resQuestion);
});
});
});
REDUX 요청을 가져 오기 :
function fetchQuestion() {
return (dispatch) => {
let url = 'http://localhost:8080/questions';
return fetch(url).then((response) => {
if (response.status < 200 || response.status >= 300) {
let error = new Error(response.statusText);
error.response = response;
throw error;
}
return response.json();
}).then((questions) => {
return dispatch(fetchQuestionsSuccess(questions));
}).catch((error) => {
return dispatch(fetchQuestionsError(error));
}
};
}