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

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

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

  1. const loginUser = async (e) => {
  2. // e.preventDefault();
  3. const res = await fetch("http://localhost:8000/login", {
  4. method: "POST",
  5. headers: {
  6. 'Content-Type': 'application/json'
  7. },
  8. body: JSON.stringify({
  9. email:email,
  10. password:password,
  11. }),
  12. });
  13. const data = await res.json();
  14. console.log("Data",data)
  15. if (data.status === 422 || !data) {
  16. console.log("Invalid cred");
  17. window.alert("Invalid Credentials");
  18. }
  19. if(data.status === 400){
  20. window.alert("wrong password");
  21. }
  22. else{
  23. window.alert("Login Suceesfuuly");
  24. console.log("Login success");
  25. history.push("/");
  26. }
  27. };

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

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

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

  1. try {
  2. const { email, password } = req.body;
  3. console.log("we got a request", email, password);
  4. if (!email || !password) {
  5. return res.status(422).json({ error: "pls filled all the field" });
  6. }
  7. const userLogin = await User.findOne({
  8. $and: [{ email: email }],
  9. });
  10. if (!userLogin) {
  11. return res.status(422).json({ error: "User is not authorized" });
  12. }
  13. if (userLogin) {
  14. const passwordMatch = await bcrypt.compare(password, userLogin.password);
  15. const token = await userLogin.generateAuthToken();
  16. res.cookie('jwtoken', token, {
  17. expires: new Date(Date.now() + 25892000000),
  18. httpOnly:true
  19. })
  20. if (passwordMatch) {
  21. return res.status(200).json({ message: "login success" });
  22. } else {
  23. return res.status(400).send({ error: "The password is invalid" });
  24. }
  25. }
  26. } catch (err) {
  27. console.log(`Error: ${err}`);
  28. }

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

  1. we got a request undefined undefined
blpfk2vs

blpfk2vs1#

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

cetgtptt

cetgtptt2#

这里发生了很多事情。

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

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

相关问题