首页 > 解决方案 > react & node API - 获取函数错误

问题描述

我只是 React 和 NodeJS 快速编程的新手,我在几个小时内都陷入了一些错误。当我尝试获取时,有时我得到了响应(但不是我的响应),有时我得到了“获取失败”。

我试图在没有太多理解的情况下理解“cors”概念,但我已经提交 app.use(cors()) 允许每个来源。

请注意,我的服务器有时会收到“OPTIONS”请求,有时会收到“POST”请求。

在我的 React 中,我有这个功能:

fetch('http://localhost:3000/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',   
        },
        body: JSON.stringify ({
          user: this.state.username,
          pass: this.state.password,
        })
      }).then(res => {
          console.log(res.msg);
      })
      .catch(function(err) {
        alert(err);
      })
}

在我的 NodeJS 我有这个功能:

router.post('/', (req, res) => {
let user = {
    username: req.body.user,
    password: req.body.pass 
}
UserModel.findOne({'username': user.username, 'password' : user.password}, function(err, user) {
    if (err) {
        res.json({
            ok: false,
            msg: 'login failed, try later'
        });
    } else if (user) {
        let token = jwt.encode(user, secret);
        res.json({
            msg: 'logged in',
            ok: true
        });
    } else {
        res.json({
            ok: false,
            msg: 'invalid input'
        });
    }
});

我很困惑,希望你能帮助我。谢谢。

标签: node.jsreactjs

解决方案


您没有正确访问响应的 JSON。您需要调用Body#json响应的方法才能真正访问 JSON 内容。另请注意,它返回一个解析为响应的 JSON 内容的承诺:

fetch('…', { … })
  .then(res => res.json())
  .then(json => {
    console.log(json.msg);
  });

另外,我建议将 HTTP 状态代码与 JSON 一起发送,而不是使用ok属性。Response这是一种标准方式,并且通过对象具有内置支持:

res.status(200).json({ … });

推荐阅读