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

One*_* T. 7 javascript error-handling plesk node.js express

我在 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
            }
          });
        }
      );
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

和我的 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}`));
Run Code Online (Sandbox Code Playgroud)

在本地主机上没有问题。但是上传到服务器后,当我留空或提交错误密码等时,它永远不会发送我的 JSON 响应,而是返回服务器 Html 页面。我 console.logged 返回错误响应,它是这样的:

在此输入图像描述

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

小智 -1

我猜你用的是axios?

你尝试过吗:

.then(err => {
   err.response.data
})
Run Code Online (Sandbox Code Playgroud)

您的回复实际上是在err.response