I have a REST api on the express server and React app for front-end. I have designed it to send JSON to front-end when faces an error, it sends it and I can use it to print errors on the client side as a modal etc. this is my route file for user/login(I also use JWT and bcrypt for password issues):
router.post("/login", (req, res) => {
const { email, password } = req.body;
//simple validation
if (!email || !password) {
return res.status(400).json({ general: "Email and Password can not be empty" });
}
//check for existing user
User.findOne({ email }).then((err, user) => {
if (!user)
return res.status(400).json({ email: "This user doesn't exist"});
if (err) console.log(err);
//Validate password
bcrypt.compare(password, user.password).then(isMatch => {
if (!isMatch)
return res
.status(400)
.json({ password: "Password and User name are not match!" });
jwt.sign(
{ id: user.id },
config.get("jwtSecret"),
{ expiresIn: 3600 },
(err, token) => {
if (err) throw err;
res.json({
token,
user: {
id: user.id,
name: user.name,
email: user.email,
sort: user.sort
}
});
}
);
});
});
});
and my app.js:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const config = require("config");
const app = express();
//Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = config.get("mongoURI");
//connect to Mongo
mongoose
.connect(db)
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
//Use routes
app.use("/api/test", require("./routes/api/test"));
app.use("/api/users", require("./routes/api/users"));
app.use("/api/tickets", require("./routes/api/tickets"));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
On Localhost there is no problem. But after uploading to the server, when I left empty spaces or submit false password etc, it never sends my JSON responses, instead, it returns servers Html Page. I console.logged returning error response and it is something like this:
How can I replace the Html response with my own JSON error message?
2
Answers
i guess you are using axios?
did you try it with:
Your response is actually in
err.response
The default error handler shows the error as an HTML page.
See https://expressjs.com/en/guide/error-handling.html
You can override the default error handler. Try adding this to the end of your app.js.