我已经设置了使用Google策略的passport,并且可以直接转到/auth/google great。我目前有它,所以当您使用谷歌身份验证oauth2登录时,我的端点将通过检查req.user进行身份验证。当我刚刚在浏览器中到达端点时,这是有效的。如果我先转到/auth/google,然后转到/questions,我将能够发出get请求。但是,当我尝试从redux发出fetch请求时,我会收到一条错误消息,提示为Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0。它的出现是因为fetch API试图到达我的/questions端点,经过我的loggedIn中间件,然后没有满足if (!req.user),而是被重定向。关于如何使用PassportJS和passport-google-oauth2从Fetch API进行身份验证,您有什么想法吗?
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 fetch请求:
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));
}
};
}发布于 2016-10-28 16:12:01
默认情况下,Fetch API不会发送cookie,Passport需要cookie来确认会话。尝试将credentials标志添加到所有获取请求,如下所示:
fetch(url, { credentials: 'include' }).then...
或者,如果您没有执行CORS请求:
fetch(url, { credentials: 'same-origin' }).then...
https://stackoverflow.com/questions/39259569
复制相似问题