【问题标题】:Unable to get data at server even after giving it correctly through body in React即使通过 React 中的正文正确提供数据,也无法在服务器上获取数据
【发布时间】:2021-10-02 22:39:39
【问题描述】:

我正在实现一个用户登录系统,但是当我向我的服务器发送请求时,我的服务器正在接收未定义的数据。首先我是通过代理进行的,但是即使在提供完整的 url 之后它也不起作用并且在提交时它也会被重定向到 http://localhost:3000/login 但它应该在成功时被重定向到主页如果它没有授权它会提醒用户。
客户端登录

const loginUser = async (e) => {
    // e.preventDefault();
    const res = await fetch("http://localhost:8000/login", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email:email,
        password:password,
      }),
    });
    const data = await res.json();
    console.log("Data",data)
    if (data.status === 422 || !data) {
      console.log("Invalid cred");
      window.alert("Invalid Credentials");
    }
    if(data.status === 400){
      window.alert("wrong password");
    }
    else{
      window.alert("Login Suceesfuuly");
      console.log("Login success");
      history.push("/");
    }
    
  };

在这种情况下,即使数据无效或未正确填写,它也应该显示警报,但它被重定向到 http://localhost:3000/login 并且给了我一些 json 响应,此页面的内容是:

{"error":"pls filled all the field"}

以及服务器端登录功能的代码
服务器端登录

 try {
    const { email, password } = req.body;
    console.log("we got a request", email, password);
    if (!email || !password) {
      return res.status(422).json({ error: "pls filled all the field" });
    }

    const userLogin = await User.findOne({
      $and: [{ email: email }],
    });
    if (!userLogin) {
      return res.status(422).json({ error: "User is not authorized" });
    }
    if (userLogin) {
      const passwordMatch = await bcrypt.compare(password, userLogin.password);
      const token =  await userLogin.generateAuthToken();
      
      res.cookie('jwtoken', token, {
          expires: new Date(Date.now() + 25892000000),
          httpOnly:true
      })
      if (passwordMatch) {
        return res.status(200).json({ message: "login success" });
      } else {
        return res.status(400).send({ error: "The password is invalid" });
      }
    }
  } catch (err) {
    console.log(`Error: ${err}`);
  }

每次我从客户端发出请求时,我都会在服务器端得到这个

we got a request undefined undefined

【问题讨论】:

  • 你在后端设置bodyparser了吗?
  • 打开开发者控制台并检查客户端请求是否有请求体——如果有,那么你的后端有问题。我看到它是 nodejs + express,所以一个想法可能是你还没有设置正文解析器。

标签: html node.js reactjs api fetch-api


【解决方案1】:

在服务器端尝试控制台记录req.body。然后在解构请求对象之前,您将知道从客户端获取的请求正文的结构。检查服务器中是否有正文解析器。而且我认为你不需要在帖子请求中做JSON.stringify()

【讨论】:

    【解决方案2】:

    这里发生了很多事情。

    if (!email || !password) {
          return res.status(422).json({ error: "pls filled all the field" });
        }
    

    您从这里得到一个错误,这意味着 emailpassword 是虚假的。您还可以通过注意您收到的电子邮件和密码为undefined 来检查这一点。

    一些尝试:

    1. 检查您的 Express 服务器是否添加了正文解析器作为中间件。
    2. 检查您是否确实从电子邮件和密码字段发送了一些数据。您可以在发送数据之前将它们登录到客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 2011-04-24
      • 1970-01-01
      • 2015-05-15
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多