Express返回服务器的自动HTML错误页面,而不是我的res.json错误消息

时间:2020-03-02 10:56:03

标签: javascript node.js express error-handling plesk

我在Express服务器上有一个REST api,前端有React应用。我将其设计为在遇到错误时将JSON发送到前端,将其发送,并且可以使用它以模态等方式在客户端打印错误。这是我的用户/登录路由文件(我也使用JWT和bcrypt来解决密码问题):

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
            }
          });
        }
      );
    });
  });
});

和我的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}`));

在Localhost上没有问题。但是上传到服务器后,当我留下空白或提交错误的密码等时,它从不发送我的JSON响应,而是返回服务器Html页。我用console.logged返回错误响应,它是这样的:

enter image description here

如何用自己的JSON错误消息替换Html响应?

2 个答案:

答案 0 :(得分:0)

默认错误处理程序将错误显示为HTML页面。

请参见https://expressjs.com/en/guide/error-handling.html

您可以覆盖默认错误处理程序。尝试将其添加到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();
});

答案 1 :(得分:-1)

我猜你在用axios吗?

您尝试使用以下方法吗:

.then(err => {
   err.response.data
})

您的回复实际上在err.response