Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express returns servers' automatic HTML error page, instead of my res.json error message

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:

enter image description here

How can I replace the Html response with my own JSON error message?

like image 330
Oner T. Avatar asked Nov 15 '22 15:11

Oner T.


1 Answers

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.

// catch 404 and forward to error handler
app.use(function (req: express.Request, res: express.Response, next) {
    next({ status: 404 });
});

app.use(function (err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
    console.error(err);
    res.status(err.status || 500).json();
});
like image 122
Dovev Hefetz Avatar answered Nov 19 '22 09:11

Dovev Hefetz