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

标签 node.js redux passport.js fetch-api passport-google-oauth2

我已将通行证设置为使用 Google 策略,并且可以直接访问/auth/google。我目前拥有它,因此当您使用 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 进行身份验证有什么想法吗?

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 需要用它来确认 session 。尝试将 credentials 标志添加到您的所有获取请求中,如下所示:

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

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

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

关于node.js - 端点未通过 Fetch API 调用进行身份验证(使用 passport-google-oauth2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39259569/

相关文章:

使用 Node.js 进行 ajax 实时搜索

javascript - 想要 ping lambda 响应时间长达 4 或 5 秒或更短

javascript - 为什么当不相关的状态发生变化时,我的 redux 容器会渲染?

javascript - Passport js,cookie过期后无法登录

node.js - 了解 Passport.js - 篡改序列化用户

Node.js/express - 使用带有 redis 的 Passport ,获取未经授权的 session

node.js - Nodejs Promise async/await 无法正常工作

node.js - 将 session 存储在express(node.js)和neo4j数据库上

redux - 测试 redux-observable 史诗的错误处理

javascript - Redux 动机 : mutation and asynchronicity with example