正如标题所示,我的 api 没有收到任何响应,而是继续加载。由于某种原因我的中间件没有被触发。例如,在下面的代码中,我尝试控制台记录随机文本,但未打印该值。
export const login = asyncErrorHandler(
async (req: Request, res: Response, next: NextFunction) => {
console.log(req.body)
const { email, password } = req.body;
console.log("hawrgag")
if (!email || !password) {
return next(new ErrorHandler("Enter all the details", 400));
}
if (!validateEmail(email)) {
return next(new ErrorHandler("Please enter correct email", 400));
}
const user = await User.findOne({ email });
if (!user) {
return next(new ErrorHandler("User doesn't exists", 400));
}
const pass = verifyPassword(password, user.password);
if (!pass) {
return next(new ErrorHandler("email or password is incorrect", 400));
}
const data = {
user: {
id: user._id,
},
};
const authtoken = generateToken(data);
return res.status(200).json({ success: true, authtoken });
}
);
看起来中间件没有被调用。我不知道问题出在哪里。 这是 asyncErrorHandler
import { Request, Response, NextFunction } from "express";
import { ControllerType } from "types/controllerType";
const asyncErrorHandler = (func: ControllerType) => {
return (req: Request, res: Response, next: NextFunction) => {
return Promise.resolve(func(req, res, next)).catch(next);
};
};
export default asyncErrorHandler;
这是我的控制器类型
import { Request, Response, NextFunction } from "express";
export type ControllerType = (
req: Request,
res: Response,
next: NextFunction
) => Promise<void | Response<any, Record<string, any>>>;
这是我的路线文件
import express from "express";
import { sendOTP, verifyOTP, signup, login } from "../controller/auth";
const router = express.Router();
router.post("/send-otp", sendOTP);
router.post("/verify-otp", verifyOTP);
router.post("/signup", signup);
router.post("/login", login);
export default router;
这是我的index.ts 文件
import express, { Express, Request, Response } from "express";
import http from "http";
import dotenv from "dotenv";
import cors from "cors";
import connect from "./db";
import auth from "./routes/auth";
import user from "./routes/user";
import { errorhandling } from "./middleware/errorhandling";
dotenv.config();
const app: Express = express();
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
const { PORT } = process.env;
const server = http.createServer();
connect();
app.use("/api/v1/auth", auth);
app.use("/api/v1/user", user);
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
请帮助我哪里出错了。
您可能打算将 Express 应用程序传递到 HTTP 服务器:
const server = http.createServer(app);
您也可以完全省略
http.createServer()
,因为 Express 会为您做到这一点:
const app: Express = express();
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
connect();
app.use("/api/v1/auth", auth);
app.use("/api/v1/user", user);
const { PORT } = process.env;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});