2016-08-31 12 views
2

パスポートはGoogle戦略を使用するように設定されており、/ auth/google greatに誘導できます。現在、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はパスポートがセッションを確認する必要がデフォルトでクッキーを送信しません。

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

か、CORS要求を行っていない場合:

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

そうのようにすべてのあなたのフェッチ要求に credentialsフラグを追加してみてください
関連する問題