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

Endpoints not authenticating with Fetch API calls (using passport-google-oauth2)

我已经设置了 passport 来使用 Google 策略并且可以直接到 /auth/google 太棒了。我目前拥有它,因此当您使用 google 身份验证 oauth2 登录时,我的端点将通过检查 req.user 来进行身份验证。当我刚到浏览器中的端点时,这会起作用。如果我转到 /auth/google,然后转到 /questions,我将能够发出该获取请求。但是,当我尝试从 redux 发出获取请求时,我会收到一条错误消息,内容为 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 获取请求:

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

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

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

或者如果您不执行 CORS 请求:

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