即使在react中通过正文正确提供数据,也无法在服务器上获取数据

91zkwejq  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(242)

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

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
blpfk2vs

blpfk2vs1#

尝试控制台日志记录 req.body 在服务器端。然后,在分解请求对象之前,您将知道从客户机获得的请求主体的结构。检查服务器中是否有主体解析器。而且我也不认为你需要这么做 JSON.stringify() 在post请求中。

cetgtptt

cetgtptt2#

这里发生了很多事情。

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

这里有个错误,也就是说 emailpassword 你是个骗子。您也可以通过注意您收到的电子邮件和密码来检查这一点 undefined .
有些事情可以尝试:
检查express服务器是否添加了主体解析器作为中间件。
检查您是否确实从电子邮件和密码字段发送了一些数据。在发送数据之前,您可以在客户端登录它们。

相关问题