имеется приложение на typescript с использованием typescript. Я пытаюсь обработать ошибки, но вместо json на выходе получаю html. Error-handler так же должен коректно выводить ошибки созданые mongo
index.ts
import express, { Express, NextFunction, Request, Response } from 'express';
import dotenv from 'dotenv';
import connectDB = require('./db/connect-db');
import { apiRouter } from './routes';
import cors from 'cors';
import { errorHandler } from './middleware/error-handler';
import createError from 'http-errors';
dotenv.config();
const app: Express = express();
const port = process.env.PORT || 3000;
try {
connectDB();
app.use(cors());
app.use(express.json());
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.log('\x1b[31m%s', String('-').repeat(50));
console.log(err.status);
console.log(`Message: ${err.message}`);
console.log(`Path: ${req.path}`);
console.log('\x1b[31m%s', String('-').repeat(50));
res
.status(err?.status || 500)
.json({ message: err.message, path: req.path, key: err.code, ...err });
});
app.use('/api', apiRouter);
} catch (e) {
console.log(e);
}
app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
});
controllers.ts
import User from '../db/models/User';
import { NextFunction, Request, Response } from 'express';
import bcrypt from 'bcrypt';
import createError from 'http-errors';
export const register = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { name, email, gender, password, birthday } = req.body;
const existingUser = await User.findOne({ email });
if (existingUser)
createError({ code: 400, message: 'Username already exists' });
const hashedPass = bcrypt.hashSync(password, 10);
const user = await User.create({
name,
email,
gender,
password: hashedPass,
birthday,
});
res.status(200).json(user);
} catch (error) {
next(error);
}
};
export const login = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { email, password } = req.body;
if (!password || !email) {
throw createHttpError(400, {
message: 'Please provide both email and password',
code: 'login - missing email or password',
});
}
const user = await User.findOne({ email });
if (!user) {
throw createHttpError(404, {
message: 'Cannot find user with provided email',
code: 'login - missing user with provided email',
});
}
const result = bcrypt.compareSync(password, user.password);
if (!result) {
throw createHttpError(401, {
message: 'Invalid email password pair',
code: 'login - invalid credentials pair',
});
}
} catch (error) {
next(error);
}
};
export const list = async (req: Request, res: Response, next: NextFunction) => {
try {
const list = await User.find();
res.status(200).json(list);
} catch (e) {
next(e);
}
};
Заголовки
{
authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NWM5ZGU1NDMzZTFkOGFkYmE2NGZmZDYiLCJuYW1lIjoiVGVzdCBVc2VyNyIsImVtYWlsIjoidGVzdDdAZ21haWwuY29tIiwiZGF0ZSI6IjIwMjQtMDItMTJUMDk6MjA6MzguMTUyWiIsImlhdCI6MTcwNzcyOTYzOH0.QbxR12psHSnonExphH-yqUasmdxstlB8hFTBkddrtZc',
'user-agent': 'PostmanRuntime/7.36.1',
accept: '*/*',
'postman-token': '1e119acc-e868-40f2-adb3-f4688f4e55fa',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate, br',
connection: 'keep-alive'
}
accept
то скорее всего надо проверять как там указаноapplication/json
а не простоjson
- если нет - то либо убрать проверку ` if (req.accepts('json')) {` и всегда отдавать json - либо добавить заголовок в запросuse
а у тебя после него добавляетсяroute
еще