Express App 返回状态代码但正文正确

问题描述 投票:0回答:1

我是新来表达的,大约几周前,我的假设是错误处理将与 springboot 一样简单。我错了。所以我用这种方式设置了这个 Express 应用程序:

  1. 请求进来并被中间件拦截,就像这样
// auth endpoint
app.use(`/api/v1/auth`, authRouter)
  1. 请求发送到路由器
// login router
router.route("/login").post(authController.handleLogin);
  1. 路由器
const handleLogin = async (req: Request, res: Response<AuthResponse>) => {
  try {
    const body: UserAuthenticationBody = req.body;
    const isAuthenticated = await authService.authenticate(body); // Assuming authenticate returns a boolean indicating authentication status
    console.log({ accessTokenSecret })
    if (isAuthenticated) {
      const user: UserDocument = await userService.getUserProfile(body.username);
      console.log(user);
      const accessToken = jwt.sign({
        _id: user._id,
        firstname: user.firstname,
        lastname: user.lastname,
        username: body.username,
      }, accessTokenSecret, { expiresIn: '2h' });

      console.log("Here-1")
      return res.status(HttpStatusCode.BAD_REQUEST).json({
        message: "Authentication successful",
        status: HttpStatusCode.OK,
        data: {
          accessToken: accessToken
        }
      });
    } else {
      console.log("Here-2")
      return res.status(401).json({
        message: "Authentication failed",
        status: HttpStatusCode.UNAUTHORIZED
      });
    }
  } catch (err: any) {
    console.log("Here-3")

    return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR).json({
      message: err.message,
      status: HttpStatusCode.INTERNAL_SERVER_ERROR
    });
  }
}
  1. 正在调用的身份验证服务
const authenticate = async (credentials: UserAuthenticationBody): Promise<boolean> => {
  try {
  const user: UserDocument | null = await User.findOne({
    $or: [
      { username: credentials.username },
      { email: credentials.username }
    ]
  });

  if (!user) {
    // User not found
    throw new Error("user does not exist");
  }

  // Compare the provided password with the hashed password stored in the database
  const passwordMatch = await bcrypt.compare(credentials.password, user.password);
  return passwordMatch;
  }
  catch (error: any) {
    console.log("error in auth");
    throw error;
  }
}

** 问题是,当找不到用户时,会抛出错误,并且确实触发了句柄登录中的 catch 子句,但响应状态正常,尽管我已指定它应该是 500 INTERNAL_SERVER_ERROR。更令人困惑的是,从响应json对象返回的消息是“用户不存在”**

我检查了枚举 INTERNAL_SERVER ERROR 的值,它是 500。 我尝试使用全局处理程序,但我认为我可能配置错误,所以我不确定我是否做得正确。

我做错了什么?

这就是我的服务器索引的其余部分的样子

import dotenv from "dotenv";
dotenv.config();

import express, { Request, Response, NextFunction } from "express";
import compression from "compression";
import cors from "cors";
import http from "http";
import { Server as SocketIoServer, Socket } from "socket.io";
import mongoose from "mongoose";
import { connectDB } from "./config/DbConfigurations";
import { ChatMessage } from "./api/v1/models";

// Connect to DB
connectDB();

const app = express();
const server = http.createServer(app);
const io = new SocketIoServer(server, {
  cors: {
    origin: "*",
    methods: "*"
  }
});
const port = process.env.PORT || 5000;

// middleware 
app.use(express.json());
// app.use(compression());

app.use(cors());

// Make sure request has a bearer token unless its 
import { authController } from "./api/v1/controllers";
// app.use(authController.authenticateToken)

import {
  authRouter,
  usersRouter,
  groupsRouter,
  journalsRouter
} from "./api/v1/routes/index";

// Error handling middleware
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error(err.stack);
  res.status(500).json({
    message: 'Internal Server Error',
    status: 500
  });
});

// auth endpoint
app.use(`/api/v1/auth`, authRouter)

// users endpoint
app.use(`/api/v1/users`, usersRouter);

// journals endpoint
app.use("/api/v1/journals", journalsRouter)

// groups  endpoint
app.use(`/api/v1/groups`, groupsRouter)

// Socket.IO connection handler
io.on('connection', (socket: Socket) => {
  console.log('A user connected');

  // Join a chat room based on the pair of users
  socket.on('joinChat', (data) => {
    console.log("Chat created")
    const { sender, receiver } = data;
    const room = [sender, receiver].sort().join('-');
    socket.join(room);
  });

  // Handle incoming messages
  socket.on('chatMessage', async (data) => {
    const { sender, receiver, content } = data;
    // Broadcast the message to the appropriate chat room
    const chatRoom = [sender, receiver].sort().join('-');
    const message = new ChatMessage({ chatRoom, sender, receiver, content, timestamp: new Date() });
    await message.save();


    io.to(chatRoom).emit('chatMessage', message);

  });

  // Handle disconnections
  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });
});

// Only if we connect to a DB should we listen to api requests
mongoose.connection.once('open', () => {
  console.log("Connected to MongoDB");
  server.listen(port, () => console.log("server listening on port: ", port));

})

javascript node.js mongodb express backend
1个回答
0
投票

我没有足够的声誉来评论你的帖子,所以我发布了一个答案,这确实发生在我身上一次,

HttpStatusCode.BAD_REQUEST
在我的项目中不起作用,我不知道为什么,所以我以 int 形式发送 400:

res.status(400)

尝试一下,让我知道这是否对你有用,否则我会删除我的答案。

© www.soinside.com 2019 - 2024. All rights reserved.