如何修复 Cannot set headers after they are sent to the client 错误?

How can I fix Cannot set headers after they are sent to the client error?

我有 2 个问题,使用 express get method 进行了搜索查询,它工作正常,它获得了请求的票证,问题是即使该方法有效,我仍然不断出错 所以第一个问题是为什么我总是收到这些错误,我该如何解决?

控制台日志:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:558:11)
    at ServerResponse.header (C:Project\server\node_modules\express\lib\response.js:771:10)       
    at ServerResponse.json (C:Project\server\node_modules\express\lib\response.js:264:10)
    at ServerResponse.send (C:Project\server\node_modules\express\lib\response.js:158:21)
    at C:Project\server\index.ts:63:7
    at Layer.handle [as handle_request] (C:Project\server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:Project\server\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:Project\server\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:Project\server\node_modules\express\lib\router\layer.js:95:5)
    at C:\Project\server\node_modules\express\lib\router\index.js:281:22

代码:

  app.get(APIPath, (req, res) => {
    //@ts-ignore
    const search:String = req.query.search;
  if(search !== undefined){
    const filteredTickets = tempData.filter((t) => (t.title.toLowerCase() + t.content.toLowerCase()).includes(search.toLowerCase()));
    res.send(filteredTickets);
  }

  // @ts-ignore
  const page: number = req.query.page || 1;

  const paginatedData = tempData.slice((page - 1) * dataProps.getPageSize(), page * dataProps.getPageSize());

  console.log("Server: Page " + page + " was sent!");
  console.log("Server: Search query: " + search)

  res.send(paginatedData);
});

如您所见,我在同一个函数中进行了 2 个查询,页面查询工作得很好,我尝试将它们组合起来的原因是我希望在搜索其他参数后仍然能够拥有页面 (页数限制为 20),但目前他们没有一起工作,因为我不知道该怎么做。 这就提出了第二个问题,我怎样才能把这两个查询结合起来,让它看起来像 https://localhost:3000/?page=[Page]/?search=[Search request]

您不能多次调用 res.send()res.send() 不会自行停止函数的执行,因此您必须手动 return。

return res.send(filteredTickets);

否则函数继续执行并进入第二个 res.send() 调用。