所有错误消息在postman中工作,但不在显示前端客户端中

hrirmatl  于 2023-06-22  发布在  Postman
关注(0)|答案(1)|浏览(144)

我正在创建一个网站使用React和节点。在我的服务器注册和登录所有邮件工作在 Postman 正常,但在显示端的注册错误显示正常,但我的登录错误没有显示(例如:用户名或密码不正确)
我需要在我的网站显示错误不是有效的密码一样。但错误信息不显示在显示后,抓住认为在登录页面。路由器登录

router.post("/login", async (req, res) => {
  const { identifier, password } = req.body;
  console.log("Login request:", identifier, password); // Log the request parameters

  const user = await UserModel.findOne({
    $or: [{ username: identifier }, { email: identifier }],
  });
  console.log("User found:", user); // Log the retrieved user

  if (!user) {
    console.log("User not found"); // Log the condition
    return res.json({ message: "User Doesn't Exist!" });
  }

  const isPasswordValid = await bcrypt.compare(password, user.password);
  console.log("Is password valid:", isPasswordValid); // Log the password comparison result

  if (!isPasswordValid) {
    console.log("Incorrect password"); // Log the condition
    return res.json({ message: "Username or Password is Incorrect" });
  }

  const token = jwt.sign({ id: user._id }, "secret");
  console.log("Login successful. Token:", token); // Log the generated token
  res.json({ token, userID: user._id });
});

这是我的登录页面

const Login = () => {
  const [password, setPassword] = useState("");
  const [identifier, setIdentifier] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const [_, setcookies] = useCookies(["access_token"]);

  const navigate = useNavigate();

  const onSubmit = async (event) => {
    event.preventDefault();
    try {
      const response = await axios.post("http://localhost:3001/auth/login", {
        identifier,
        password,
      });
      console.log("Login Response:", response.data);

      setcookies("access_token", response.data.token);
      window.localStorage.setItem("userID", response.data.userID);
      navigate("/");
    } catch (err) {
      console.error(err.response.data);
      setErrorMessage(err.response.data.message);
      console.log("Error Message:", err.response.data.message);
    }
  };
  return (
    <div className="sign-text-content">
      <div className="text-full">
        <div className="text-content">
          <img src="Group1.svg" alt="img" />{" "}
        </div>
        <span className="plan">
          {" "}
          <img src="planGroup20.svg" alt="imgae" />
        </span>
      </div>
      <div className="bluesign"> </div>
      <Form className="register-form" action="" onSubmit={onSubmit}>
        <span className="welcome">
          {" "}
          <img src="welcome.svg" alt="im" />{" "}
        </span>
        <Form.Group className="form-group" controlId="identifier">
          <Form.Label className="text-uppercase"></Form.Label>
          <Form.Control
            type="text"
            className="form-control"
            value={identifier}
            onChange={(event) => setIdentifier(event.target.value)}
            placeholder="Username or Email"
          />
        </Form.Group>
        <Form.Group className="form-group" controlId="password">
          <Form.Label className="text-uppercase"></Form.Label>
          <Form.Control
            className="form-control"
            type="password"
            onChange={(event) => setPassword(event.target.value)}
            value={password}
            placeholder="Password"
          />
          {errorMessage && <div className="text-danger">{errorMessage}</div>}
          <Button
            variant="primary"
            type="submit"
            id="btn-log"
            className="btn btn-login float-right"
          >
            Login
          </Button>
        </Form.Group>
        <div className="clearfix"></div>
        <div className="form-group">
          Create new account ? Please <Link to="/auth">Register</Link>
        </div>
      </Form>
    </div>
  );
};

在我的控制台显示登录
响应:对象消息:“用户不存在!"

pgccezyw

pgccezyw1#

默认情况下,只要目标服务器响应4XX / 5XX错误,axios HTTP库就会抛出错误。
在您的示例中,服务器将以默认的成功状态(200)进行响应。
因此,使用适当的状态进行响应,以在客户端抛出错误。

router.post("/login", async (req, res) => {
  const { identifier, password } = req.body;
  console.log("Login request:", identifier, password); // Log the request parameters

  const user = await UserModel.findOne({
    $or: [{ username: identifier }, { email: identifier }],
  });
  console.log("User found:", user); // Log the retrieved user

  if (!user) {
    console.log("User not found"); // Log the condition
    return res.status(404).json({ message: "User Doesn't Exist!" });
  }

  const isPasswordValid = await bcrypt.compare(password, user.password);
  console.log("Is password valid:", isPasswordValid); // Log the password comparison result

  if (!isPasswordValid) {
    console.log("Incorrect password"); // Log the condition
    return res.status(401).json({ message: "Username or Password is Incorrect" });
  }

  const token = jwt.sign({ id: user._id }, "secret");
  console.log("Login successful. Token:", token); // Log the generated token
  res.json({ token, userID: user._id });
});

相关问题