代码之家  ›  专栏  ›  技术社区  ›  maison.m

NodeJs-来自客户端的fetch请求总是从服务器返回200状态响应,而不管更新数据库时是否出错

  •  0
  • maison.m  · 技术社区  · 6 年前

    我正在使用 fetch() 客户端请求将更新的用户数据放入后端,然后保存到数据库中。到目前为止,所有路线都运行良好,经过邮递员的验证和测试。

    在这个 User Update if 语句,该语句在数据库中搜索用户时检查错误,如果抛出此错误,它将向客户端发送404响应和消息。

    fetch() 从客户端到此路由的请求,无论是否有错误,响应始终为状态200,并且不包括来自我的路由的任何响应。我需要客户端能够处理路由可能产生的潜在错误。例如,对于此用户更新路由,如果由于任何原因在数据库中找不到该用户,将返回一个错误和消息,因此客户端需要知道这一点。

    下面是一些代码:

    客户端:

    fetch(`http://localhost:3000/users/${userId}`, {
            method: "put",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            body: JSON.stringify(userData)
          }).then(response => console.log(response))
            .catch(err => console.log(err));
    

    在客户端,我正在使用 console.log() 想象一切。当响应返回时,我返回:

    Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 200, ok: true, …}
    

    服务器端路由控制器:

    exports.user_update = (req, res) => {
      const { params, body } = req;
      const { userid } = params;
    
      User.findByIdAndUpdate({ _id: userid }, body, { new: true }, (err, user) => {
        if (err)
          res.send({
            status: 404,
            message:
              "There was an issue finding and updating the user on the server."
          });
        else
          res.send({
            status: 200,
            user
          });
      });
    };
    

    fetch() 200 ok 回答只是让我知道答案 连接到路线。这条路线(以及其他路线)已经在邮递员中进行了测试,所有的工作都按照预期返回了预期的响应。

    fetch() 这样的要求有错吗?我觉得我可能很接近,但那只是我无知的猜测。感谢阅读!

    3 回复  |  直到 6 年前
        1
  •  0
  •   Vasyl Moskalov    6 年前

    根据 express documentation 您将状态作为JSON字段发送。要正确发送http状态,请替换 res.send(...) 具有

    res.status(404).send("There was an issue finding and updating the user on the server.");
    

    res.send(user);
    
        2
  •  0
  •   Revanth M    6 年前

    status 有效负载中的字段,该字段不由 fetch 应用程序编程接口。

    要解决这个问题,你可以做如下的事情

    exports.user_update = (req, res) => {
      const { params, body } = req;
      const { userid } = params;
    
      User.findByIdAndUpdate({ _id: userid }, body, { new: true }, (err, user) => 
      {
        if (err)    
          res.status(404).send({
            message: "There was an issue finding and updating the user on the server."
          });
        else
          res.status(200).send({
            user
          });
    
      });
    };
    
        3
  •  0
  •   maison.m    6 年前

    提取请求错误,以下是更新:

    fetch(`http://localhost:3000/users/${userId}`, {
            method: "put",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            body: JSON.stringify(userData)
    
          }).then(response => response.json())
            .then(response => console.log(response))
            .catch(err => console.log(err));
    

    response.json()