2

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)); 
    } 
    }; 
} 

답변

4

페치 API는 여권가 세션을 확인 할 필요가 기본적으로 쿠키를 전송하지 않습니다. 당신이 CORS 요청을 수행하지 않는 경우

fetch(url, { credentials: 'include' }).then...

또는 : 그래서 같은 모든 당신의 인출 요청에 credentials 플래그를 추가하십시오

fetch(url, { credentials: 'same-origin' }).then...