You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express+ViteExpress环境下next(error)返回HTML响应的问题解决

404错误返回HTML而非JSON格式的问题解决

我正在编写处理无效端点的404状态码中间件,使用Postman测试时响应体为HTML,但我期望仅返回纯错误信息。当前技术栈为Vite及Express封装工具ViteExpress。

路由控制器逻辑

import { NextFunction, Request, Response } from "express";

//MongoDB Schema Import
import { Project } from "../models/projectsMod";

const allProjects = async (req: Request, res: Response, next: NextFunction) => {
  const findProjects = await Project.find();
  try {
    res.json({ message: "Success.", count: findProjects.length, projects: findProjects });
  } catch (error) {
    next(error)
  }
};

export { allProjects }

原中间件逻辑

import { Request, Response, NextFunction } from "express";


const notFoundHandler = (req: Request, res: Response, next: NextFunction) => {
   const error = new Error(`${req.method} ${req.originalUrl} not found.`)
   error['status'] = 404
   next(error)
};

export { notFoundHandler };

服务器逻辑

import * as dotenv from "dotenv";
dotenv.config();
import express from "express";
import ViteExpress from "vite-express";
import bodyParser from "body-parser";
import mongoose from "mongoose";

//MongoDB Config Import
import { databaseConnection } from "./db/config";

//Route Import
import routes from "./routes/index";

//Middleware Import
import logger from "./middleware/logging";
import { notFoundHandler } from "./middleware/errorHandler";

//Application Instance
const app = express();

//Database Connection
databaseConnection();

app.use(express.json());
app.use(bodyParser.json());
app.use(logger);
app.use(routes);
app.use(notFoundHandler)

//typecast process.env as number; default type is string | undefined
const PORT = Number(process.env.PORT || 3000);

mongoose.connection.once("open", () => {
  console.log(`MongoDB Connection: ${mongoose.connection.host}`);
  ViteExpress.listen(app, PORT, () =>
    console.log(`Server is running on: ${PORT}`)
  );
});

逻辑功能正常,但返回HTML而非纯错误信息的问题不符合预期,寻求解决建议。

更新说明

感谢建议!我意识到未将next(error)传递给另一个用于设置响应格式的中间件,以下是更新后的代码:

import { Request, Response, NextFunction } from "express";


const notFoundHandler = (req: Request, res: Response, next: NextFunction) => {
   const error = new Error(`${req.method} ${req.originalUrl} not found.`)
   error['status'] = 404
   next(error)
};

const globalErrorHandler = (error: Error, req: Request, res: Response, next: NextFunction) => {
   res.status(error['status'] || 500)
   res.json({ error: error.message })
}

export { notFoundHandler, globalErrorHandler };

内容的提问来源于stack exchange,提问作者user21876042

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:45:44