ERR_HTTP_HEADERS_SENT ExpressJS

时间:2019-09-12 07:31:57

标签: node.js express http-headers

我正在创建一个API,该API首先检查一个表中的test_set_id,然后如果发现从另一个表中获取更多数据。

如果提供的test_set_id不存在/不正确,则会发送错误,并且在找不到创建者ID的测试时

因此,我遇到以下错误。我得到的响应是正确的,但是我想更正确地了解内部工作原理,所以我想了解该错误以及如何避免该错误。

到目前为止,我的理解是我没有正确处理Promise函数,并且缺少某些东西。

我不认为我的实现是错误的,如果有人可以帮助我,我会很高兴的方式。

错误如下:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:482:11)
    at ServerResponse.header (/home/siddhant/Projects/CreateTestAPI/create-test-api/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/siddhant/Projects/CreateTestAPI/create-test-api/node_modules/express/lib/response.js:170:12)
    at connection.query.then.then.then (/home/siddhant/Projects/CreateTestAPI/create-test-api/routes/create-test.js:228:19)
    at processTicksAndRejections (internal/process/task_queues.js:86:5)
GET /admin/test-overview 200 2.635 ms - 72

API代码如下

   const corp_id = request.body.creator_id;
   const academic_id = request.body.academic_id;
   var connection = new promise_database.Database();
   var result = {};

   const statement_1 = `SELECT id, academic_id, candidate_id, created_at, question_id
   FROM m_edu.custom_test_history_students WHERE academic_id = '${academic_id}'```

   const statement_2 = `SELECT test_set_id
   FROM m_edu.test_created_history WHERE test_creator_details_id = '${corp_id}'`

   connection.query(statement_2)
      .then(rows => {
         if (Object.keys(rows).length === 0) {
            result.status = "Not OK";
            result.message = "No Tests has been created till now";
            result.code = 142706
            response.send(result)
         } else {
            count = 0
            for (i = 0; i < Object.keys(rows).length; i++) {
               if (rows[i].test_set_id == academic_id) {
                  count++
               }
               if (count > 0) {
                  return connection.query(statement_1);
               } else {
                  result.status = "No Such Test";
                  result.message = "Please check again for test_set_id"
                  response.send(result)
               }
            }

         }
      }, error => {
         console.log(error);
         result.status = "Server Error";
         result.message = "Please Contact Server Admin";
         result.code = 142708;
         response.send(result);
      }).then(rows => {
         console.log(rows)
      }, error => {

      }).then(() => {
         response.send("Done")
      }).catch (error => {
         console.log(error) //line 228
      })
});

如果test_set_id匹配,则可以正常工作。

1 个答案:

答案 0 :(得分:2)

如果您没有匹配行,则尝试发送2个响应。 if语句then中的第一个,最后一个response.send("Done") from django.contrib.auth.models import AbstractUser class User(AbstractUser): def __str__(self): return self.username 中的第二个。