首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未使用Fetch API调用进行身份验证的端点(使用passport-google-oauth2)

未使用Fetch API调用进行身份验证的端点(使用passport-google-oauth2)
EN

Stack Overflow用户
提问于 2016-09-01 05:52:11
回答 1查看 1.9K关注 0票数 3

我已经设置了使用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函数:

代码语言:javascript
复制
function loggedIn(req, res, next) {
  if (req.user) {
    next();
  } else {
    res.redirect('/');
  }
}

下面是我的“GET”端点的代码。

代码语言:javascript
复制
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请求:

代码语言:javascript
复制
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));
    }  
  };
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-28 16:12:01

默认情况下,Fetch API不会发送cookie,Passport需要cookie来确认会话。尝试将credentials标志添加到所有获取请求,如下所示:

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

或者,如果您没有执行CORS请求:

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39259569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档