【问题标题】:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Api express ts错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端 Api express ts 后无法设置标头
【发布时间】:2022-02-22 21:02:14
【问题描述】:

我创建了一个过滤系统API typescript express node mongoose,我的代码有错误 (错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头),有没有人可以帮助我,附上控制器代码、实用程序和错误。谢谢。

Utils.ts

class sortPageUtils {
    constructor() { }

    paginateArray(array: any, perPage: any, page: any) {
        return array.slice((page - 1) * perPage, page * perPage)
    }

    sortCompare(key: any) {
        return (a: any, b: any) => {
            const fieldA = a[key]
            const fieldB = b[key]

            let comparison = 0
            if (fieldA > fieldB) {
                comparison = 1
            } else if (fieldA < fieldB) {
                comparison = -1
            }
            return comparison
        }
    }
}

const sort_Page = new sortPageUtils()

export default sort_Page

Controller.ts

GetAllUsers = (req: Request, res: Response, query: any) => {
        Users.find(query || {})
            .then(user => {
                // search and pagination with params config
                const {
                    q = '',
                    perPage = 10,
                    page = 1,
                    sortBy = '_id',
                    sortDesc = false,
                } = req.query;

                const queryLowered = q.toLowerCase()
                const filteredData = user.filter(item => {
                    item.nom.toLowerCase().includes(queryLowered) || item.prenom.toLowerCase().includes(queryLowered) || item.telephone.toLowerCase().includes(queryLowered) || item.email.toLowerCase().includes(queryLowered) || item.role.toLowerCase().includes(queryLowered)
                })

                const sortedData = filteredData.sort(sort_Page.sortCompare(sortBy))
                if (sortDesc) sortedData.reverse()
                res.setHeader('Content-Type', 'application/json');
                res.status(200).json({
                    users: sort_Page.paginateArray(sortedData, perPage, page),
                    total: filteredData.length,
                })
                res.end();

            })
            .catch(err => {
                res.setHeader('Content-Type', 'application/json');
                res.json({ succ1ess: false, message: err });
                res.end();

            });
    }

错误 error

更新 model.ts

import mongoose from "mongoose"
import bcrypt from "bcryptjs"
import { array } from "@hapi/joi"


const shema: any = mongoose.Schema

export interface IUser extends mongoose.Document {
    nom: string;
    prenom: string;
    fullname: string;
    telephone: string;
    genre: string;
    date_naissance: string;
    email: string;
    password: string;
    role: string;
    ability: string;
    isActive: boolean;
    encryptPassword(password: string): Promise<string>;
    validatePassword(password: string): Promise<boolean>;
}

const usersShema = new shema({
    nom: {
        type: String,
        required: true,
    },
    prenom: {
        type: String,
        required: true,
    },
    telephone: {
        type: String,
        required: true,
        unique: true,
        sparse: true,
    },
    genre: {
        type: String,
        required: true,
        enum: ['homme', 'femme']
    },
    date_naissance: {
        type: Date,
        required: false
    },
    email: {
        type: String,
        required: false,
        unique: true,
        sparse: true,
    },
    password: {
        type: String,
        required: true,
        min: [6, 'Le mot de passe doit contenir au moins 6 caractères'],
    },
    role: {
        type: String,
        required: true,
        enum: ['superadmin', 'admin', 'comptable', 'logistique', 'encadreur']
    },
    ability: {
        type: Array,
        required: true,
    },
    isActive: {
        type: Boolean,
        required: true,
        default: true
    }
}, { _id: true, timestamps: true })


usersShema.methods.encryptPassword = async (password: string): Promise<string> => {
    const salt = await bcrypt.genSalt(10)
    return bcrypt.hash(password, salt)
}
usersShema.methods.validatePassword = async function (password: string): Promise<Boolean> {
    return await bcrypt.compare(password, this.password)
}

const Users = mongoose.model<IUser>('User', usersShema)

export default Users

route.ts

import { Router } from 'express';
import userController from '../controller/UsersAuth.Controller';
import validationToken from '../libs/verifyToken'

class usersRouter {

    router: Router;

    constructor() {
        this.router = Router();
        this.routes();
    }

    routes() {

        this.router.post('/add', userController.AddUser) //Create
        this.router.post('/login', userController.Login) //Route login
        this.router.get('/profile', validationToken.TokenValidation, userController.profile) //Route profile
        this.router.get('/userEmail/:email', userController.GetUser)
        this.router.get('/list', userController.GetAllUsers)

    }
}

export default new usersRouter().router;

呼叫路线

this.app.use("/api/auth", usersRouter)

【问题讨论】:

    标签: node.js typescript mongodb express


    【解决方案1】:

    从错误消息来看,您似乎是在编写部分正文后设置标题(此处解释:Error: Can't set headers after they are sent to the client)。

    它会认为错误出现在catch 块中,您在该块中调用res.setHeader。尝试注释掉该行,看看错误是否仍然存在。

    【讨论】:

    • 感谢您的回答,我已经尝试关注此链接但没有任何变化,我已经添加了“返回”但没有任何变化。希望有新的回答,谢谢
    • 看这段代码很难说问题出在哪里。您应该尝试找出应用程序中的哪一行导致错误。它也可能在您在此处粘贴的代码之外。可能是在 GetAllUsers 控制器及其外部同时处理响应。您可以先注释掉 setHeader 部分,然后查看哪个部分导致了错误,或者您可以使用例如 VS 代码来调试您的代码。
    • 我查看了堆栈跟踪并相应地更新了我的答案。希望它有助于解决问题。
    • 错误在 .catch 中,除了当我删除 .catch 时,它处于状态(200),我按照你说的做了,但没有任何改变,在我的情况下,我只使用它仅在此控制器中的 GetAllUsers 中,我评论了 setHeader 但没有任何变化。我一直感谢您的帮助。
    • status(200).json 本身设置了 content-type 标头,所以我想这就是为什么在您删除控制器中的另一个 setHeader 后会出现错误的原因。无论如何,对我来说,问题似乎不在 GetAllUsers 控制器中,而是在它之外,即使响应已传递给控制器​​,它也会被处理和写入。这是我认为的核心问题,但是由于您没有在控制器外部共享代码,因此无法准确说出问题所在。
    猜你喜欢
    • 2019-12-11
    • 2019-12-25
    • 2022-11-30
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2022-11-03
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多