nodejs框架之Express错误:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clie

错误代码:

(node:16292) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
   

【非常重要】错误原因:Express的

res.send() 或res.json()这类客户端返回的方法仅返回一次,如果多次返回就会出现这个错误!

你的方法还api方法还是内部方法需要做一个判断,如果遇到错误才直接返回客户端,非错误,在内部方法是不能返回客户端的!

 

案例分享:

 static async deleteCodeFromRedis (res, phone_number, isApi = false) {
        let result = await ExpressBaseCRUD.expressRequestServerHandleCRUD(res,
            nodeAdminServerConfig.sms.delete_code_from_redis, {
                phone_number: phone_number,
            });
        console.log(`从redis删除手机号${phone_number}的验证码code成功`);
        // 如果是api访问,不管成功还是失败,直接返回客户端!
        if (isApi) {
            return OwnExpressResponse.resultSuccessOrFail(res,
                result, "code删除成功", "code删除失败");
        }
        return result || OwnExpressResponse.fail(res, "code删除失败");
    }

 

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个错误通常在 Express 或其他 Node.js Web 框架中出现,它表示在向客户端发送响应后,尝试设置响应头会导致错误。这通常是因为你在发送响应后仍然尝试修改响应头。 下面是一些可能导致此错误的常见原因和解决方法: 1. 在发送响应后继续发送响应或设置响应头。 Make sure that you are not sending or setting response headers after sending the response. You should only set response headers before sending the response. 2. 在使用 Express 或其他框架时,在中间件或路由处理程序中意外地多次发送响应。 Check your middleware and route handlers to make sure that you are only sending the response once. You can use a flag or variable to keep track of whether the response has already been sent. 3. 在响应已经被发送后,尝试发送另一个响应或重定向。 Make sure that you are not sending another response or redirect after the response has already been sent. You should only send one response per request. 4. 在处理 POST 请求时,使用了重复的 bodyParser 中间件。 If you are using the bodyParser middleware to parse POST requests, make sure that you are only using it once per request. 5. 在使用 Node.js 内置的 http 模块时,使用了多个 res.write() 或 res.end()。 If you are using the built-in http module in Node.js, make sure that you are only calling res.write() or res.end() once per response. 希望这些解决方案能帮助你解决这个问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值