首页 > 解决方案 > (节点:9464)UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头

问题描述

嗨,我正在尝试编写 mocha chai 测试来测试过期的 jwt 是否可以创建新条目

 it("Should NOT Allow user to create a new diary entry with an expired Token", done => {
  const entryTestData5 = {
    title: "diary",
    detail: "my new diary"
  };
  const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmaXJzdE5hbWUiOiJmaXJzdE5hbWUiLCJsYXN0TmFtZSI6Imxhc3ROYW1lIiwiZW1haWwiOiJleGFtcGxlQGdtYWlsLmNvbSIsInJlbWluZGVyIjoib2ZmIiwiaWF0IjoxNTcxOTEyOTc2LCJleHAiOjE1NzE5MTI5Nzh9.2ETTnItxbaPJiAcDubq2fxSr6SXcPEo3VN8lcjVcl7M";
  chai
    .request(app)
    .post("/api/v1/entry")
    .set("auth", token)
    .send(entryTestData5)
    .end((err, res) => {
      expect(res).to.have.status(403);
      expect(res.body).to.have.property("message");
      done();
    });
});

我在尝试运行测试时收到以下警告

(node:9464) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (C:\Users\PRO\Desktop\API\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\PRO\Desktop\API\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\PRO\Desktop\API\node_modules\express\lib\response.js:267:15)
at ServerResponse.send (C:\Users\PRO\Desktop\API\node_modules\express\lib\response.js:158:21)
at _callee$ (C:\Users\PRO\Desktop\API\Server\middleware\authenticate.js:1:7679)
at tryCatch (C:\Users\PRO\Desktop\API\node_modules\regenerator-runtime\runtime.js:45:40)
at Generator.invoke [as _invoke] (C:\Users\PRO\Desktop\API\node_modules\regenerator-runtime\runtime.js:271:22)
at Generator.prototype.(anonymous function) [as next] (C:\Users\PRO\Desktop\API\node_modules\regenerator-runtime\runtime.js:97:21)
at asyncGeneratorStep (C:\Users\PRO\Desktop\API\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (C:\Users\PRO\Desktop\API\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at process._tickCallback (internal/process/next_tick.js:68:7)

(节点:9464)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。(拒绝 ID:1)(节点:9464)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

如果有人可以帮忙,请做

以下是我的服务器

import jwt from "jsonwebtoken";
import userModel from "../models/User";

async function checkToken(req, res, next) {
 const token = await req.headers.auth; 
 let InUserEmail;
 if (typeof token !== "undefined") { jwt.verify(token, process.env.SECRET, (err, result) => {
     if (err) {
       if (err.name === "TokenExpiredError") {
         return res.status(403).send({
           message: "TokenExpired"
         });
       }
     } else {
       InUserEmail = result.email;
       req.tokenData = jwt.verify(token, process.env.SECRET);
     }
   });
   const authUser = userModel.users.find(user => user.email === InUserEmail);
   if (!authUser) {
     return res.status(401).send({
       message: "not authorized to do the task"
     });
   } next();
 } else {
   res.status(403).send({
       message: "not authorized to do the task(forbidden)"
     });
}}
export default checkToken;

标签: node.jsjwt

解决方案


推荐阅读