When making an ajax call to insert users into the database, I want to handle the response in a specific way.
If I use res.send() on the server side, it displays the response at the top left of a black document, which is not ideal.
I attempted to use return but encountered issues, so I'm seeking an alternative solution.
Client Side
$.ajax({
url: "/register",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ data: data }),
success: function (response) {
console.log(response);
Swal.fire({
title: "Success!",
text: "All good",
icon: "success",
});
},
error: function (e) {
Swal.fire({
title: "Error!",
text: "There was an error saving to the database",
icon: "error",
});
console.log(e);
},
});
Server Side
router.post("/", async (req, res) => {
req.body = sanitize(req.body);
const user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try {
await user.save();
res.status(200).send("Success");
} catch (e) {
res.status(500).send("Error");
// Add logic for handling save failure here
}
});