パスポートは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));
}
};
}