nodejs-无法全局搜索无法设置的标头

时间:2018-10-23 16:27:24

标签: node.js

我尝试对数据库中的所有方案进行全局搜索,以找到医生或医院。

const express = require("express");
const app = express();
const Hospital = require("../models/hospital");
const Medico = require("../models/medico");

  app.get("/busqueda/todo/:busqueda", async (req, res, next) => {
  var busqueda = req.params.busqueda;
  var rex = new RegExp(busqueda, "i");

  try {
    let buscaHosp = await Hospital.find({ nombre: rex }, (err, hospitales) => {
      return res.status(200).json({
        ok: true,
        hospitales: hospitales
      });
    });

    if (!buscaHosp) {
      res.json({
        ok: false,
        message: "No hospital."
      });
      return;
    } else {
      let buscarMed = await Medico.find({ nombre: rex }, (err, medicos) => {
        return res.status(200).json({
          ok: true,
          medicos: medicos
        });
      });
    }
  } catch (error) {
    next(error);
  }
});

busqueda.js

它抛出此错误:

  

错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后,无法设置标头       在ServerResponse.setHeader(_http_outgoing.js:469:11)       在ServerResponse.header(C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ node_modules \ express \ lib \ response.js:767:10)       在ServerResponse.send(C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ node_modules \ express \ lib \ response.js:170:12)       在ServerResponse.json(C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ node_modules \ express \ lib \ response.js:267:15)       在Medico.find(C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ server \ routes \ busqueda.js:38:32)       在C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ node_modules \ mongoose \ lib \ model.js:4530:16       在process.nextTick(C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ node_modules \ mongoose \ lib \ helpers \ query \ completeMany.js:35:39)       在process._tickCallback(内部/进程/next_tick.js:61:11)   在以下位置发出了“错误”事件:       在C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ node_modules \ mongoose \ lib \ model.js:4532:13       在process.nextTick(C:\ Users \ Leonardo Barahona \ Desktop \ angular-adv \ restserver-adminpro \ node_modules \ mongoose \ lib \ helpers \ query \ completeMany.js:35:39)       在process._tickCallback(internal / process / next_tick.js:61:11)

1 个答案:

答案 0 :(得分:0)

这是因为您两次设置了响应

它将始终设置为

 let buscaHosp = await Hospital.find({ nombre: rex }, (err, hospitales) => {
      return res.status(200).json({
        ok: true,
        hospitales: hospitales
      });
    });

相反,您应该通过使用名为response = {};的函数范围变量来构建返回对象。

然后执行response = await Hospital.find({ nombre: rex }, (err, hospitales) => {});

返回值为

return {
  ok: true,
  hospitales: hospitales
};

对于其他情况,只需将此变量设置为正确的值,然后在函数末尾只需运行res.status(200).json(response);