显示了一个从服务器端到客户端的警告框



我正在制作一个CRUD应用程序,它工作得非常好。现在我试图向前端显示用户输入的FirstName是否已经存在。现在我可以使用console.log()打印以下消息但是我想在客户端显示它,比如启用一些div或显示一个包含"用户名已经存在"消息的对话框。

这是我的客户端文件:
import React, { useEffect } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import "./AddEdit.css";
import axios from "axios";
import { toast } from "react-toastify";
import Container from "react-bootstrap/Container";
import Form from "react-bootstrap/Form";
import { useState } from "react";
const initialState = {
FirstName: "",
LastName: "",
FatherName: "",
userCNIC: "",
Contact: "",
Gender: "",
};
const AddEdit = () => {
const [state, setState] = useState(initialState);
const { FirstName, LastName, FatherName, userCNIC, Contact, Gender } = state;
const [gender, setGender] = useState();
const navigate = useNavigate();
const { id } = useParams();
// this useEffect will run when we have the id
// when we have the id, this basically means we are updating the content.
useEffect(() => {
axios
.get(`http://localhost:5000/api/get/${id}`)
// here we will get the response in the form of array, that will contain only one data.
// as it is fetching only single row based on the id.
.then((resp) => setState({ ...resp.data[0] }));
}, [id]);
const handleSubmit = (e) => {
var phoneno = /^d{11,12}$/;
var cnicno = /^d{12,13}$/;
// var console = window.console;
// var console = global.console;
// console.log = function (msg) {
//   if (msg.includes("FirstName already exists!")) myFunc();
// };
// function myFunc() {
//   alert("function invoked");
// }

// to prevent the default behavior of the browser.
e.preventDefault();

if (!Contact.match(phoneno)) {
// checking phone validation
toast.error("Please provide correct phone number!");
e.preventDefault();
} else if (!userCNIC.match(cnicno)) {
// checking phone validation
toast.error("Please provide correct CNIC Number!");
e.preventDefault();
} else {
// if user has no id, it means it is only adding the record.
if (!id) {
axios
.post("http://localhost:5000/api/post", {
FirstName,
LastName,
FatherName,
userCNIC,
Contact,
Gender,
})
// once user is successfully able to pass the data to database, then clear the each input field.
.then(() => {
setState({
FirstName: "",
LastName: "",
FatherName: "",
userCNIC: "",
Contact: "",
Gender: "",
});
})
.catch((err) => toast.error(err.response.data));
toast.success("Contact added Successfully");
} else {
// else it is updating the record.
axios
.put(`http://localhost:5000/api/update/${id}`, {
FirstName,
LastName,
FatherName,
userCNIC,
Contact,
Gender,
})
.then(() => {
setState({
FirstName: "",
LastName: "",
FatherName: "",
userCNIC: "",
Contact: "",
Gender: "",
});
})
.catch((err) => toast.error(err.response.data));
toast.success("Contact Updated Successfully");
}
// when all the data is submitted, navigate to the home page.
setTimeout(() => navigate("/"), 500);
}
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setState({ ...state, [name]: value });
};
return (
<div style={{ marginTop: "50px" }}>
<h1>Enter Student Details</h1>
<Container>
<Form onSubmit={handleSubmit} className="form">
<Form.Group controlId="form.Name">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter name"
name="FirstName"
onChange={handleInputChange}
value={FirstName || ""}
id="FirstName"
/>
</Form.Group>
<Form.Group controlId="form.Name">
<Form.Label>last name</Form.Label>
<Form.Control
type="text"
id="LastName"
name="LastName"
placeholder="Last Name"
value={LastName || ""}
onChange={handleInputChange}
/>
</Form.Group>
<Form.Group controlId="form.Name">
<Form.Label>father name</Form.Label>
<Form.Control
type="text"
id="FatherName"
name="FatherName"
placeholder="Fathers name:"
value={FatherName || ""}
onChange={handleInputChange}
/>
</Form.Group>
<Form.Group controlId="form.Name">
<Form.Label>CNIC name</Form.Label>
<Form.Control
type="text"
id="userCNIC"
name="userCNIC"
placeholder="CNIC:"
value={userCNIC || ""}
onChange={handleInputChange}
/>
</Form.Group>
<Form.Group controlId="form.Name">
<Form.Label>Contact name</Form.Label>
<Form.Control
type="text"
id="Contact"
name="Contact"
placeholder="Contact number"
value={Contact || ""}
onChange={handleInputChange}
/>
</Form.Group>
<Form.Group controlId="form.Name">
<Form.Label>Gender name</Form.Label>
<Form.Control
type="text"
id="Gender"
name="Gender"
placeholder="Gender:"
value={Gender || ""}
onChange={handleInputChange}
/>
</Form.Group>
<input type="submit" value={id ? "Update" : "Save"} />
<Link to="/">
<input type="button" value="Go Back" />
</Link>
</Form>
</Container>
</div>
);
};
export default AddEdit;

这是客户端的post方法文件中显示错误'FirstName已经存在'

// to add the record in the database.
app.post("/api/post", (req, res) => {
// values we will pass from the front end and recieve in the req.body.
const { FirstName, LastName, FatherName, userCNIC, Contact, Gender } =
req.body;
const sqlGet = "SELECT id FROM emp_table WHERE FirstName = ?";
db.query(sqlGet, FirstName, (error, result) => {
if (result) {
console.log("FirstName already exists!");
} else {
const sqlInsert =
"INSERT INTO emp_table (FirstName, LastName, FatherName, userCNIC, Contact, Gender) VALUES (?, ?, ?, ?, ?, ?)";
db.query(
sqlInsert,
[FirstName, LastName, FatherName, userCNIC, Contact, Gender],
(error, result) => {
if (error) {
console.log(error);
} else {
res.send("Values inserted!");
}
}
);
}
});
});

您需要向客户端发送错误响应,因为我在下面的代码中添加了:-

app.post("/api/post", (req, res) => {
// values we will pass from the front end and recieve in the req.body.
const { FirstName, LastName, FatherName, userCNIC, Contact, Gender } =
req.body;
const sqlGet = "SELECT id FROM emp_table WHERE FirstName = ?";
db.query(sqlGet, FirstName, (error, result) => {
if (result) {
console.log("FirstName already exists!");
return res.status(422).send("FirstName already exists!");
} else {
const sqlInsert =
"INSERT INTO emp_table (FirstName, LastName, FatherName, userCNIC, Contact, Gender) VALUES (?, ?, ?, ?, ?, ?)";
db.query(
sqlInsert,
[FirstName, LastName, FatherName, userCNIC, Contact, Gender],
(error, result) => {
if (error) {
console.log(error);
} else {
res.send("Values inserted!");
}
}
);
}
});
});

最新更新