How on earth should the res.json of express be returned correctly?

in express development, we often encounter a problem:

    User.findOne({
      userName: userName
    }, function (userErr, userDoc) {
      if (userErr) {
        return res.json({
          status: "0",
          msg: userErr.message,
          result: ""
        })
      } else {
        return res.json({
          status: "1",
          msg: "",
          result: "user-error"
        })
      }
    })

it keeps reporting this error:

Error: Can"t set headers after they are sent.

could you tell me how to solve this? You can"t even add return? How to do it.

add: the complete code of this interface:

router.post("/register", function (req, res, next) {
  console.log(req.body);
  if (req.body) {
    //
    function CurrentTime() {
      var now = new Date();

      var year = now.getFullYear(); //
      var month = now.getMonth() + 1; //
      var day = now.getDate(); //

      var hh = now.getHours(); //
      var mm = now.getMinutes(); //

      var clock = year + "-";
      // var clock = "";

      if (month < 10)
        clock += "0";

      clock += month + "-";

      if (day < 10)
        clock += "0";

      clock += day + " ";

      if (hh < 10)
        clock += "0";

      clock += hh + ":";
      if (mm < 10) clock += "0";
      clock += mm;
      return (clock);
    };

    //
    let userName = req.body.name;
    User.findOne({
      userName: userName
    }, function (userErr, userDoc) {
      console.log("userDoc err")
      if (userErr) {
        console.log(":"+userName);
      } else {
        res.json({
          status: "1",
          msg: "",
          result: "user-error"
        })
        return false;
      }
    })

    //
    let userPassword = req.body.pass;
    let userCheckPassword = req.body.checkPass;
    if (userPassword == userCheckPassword) {
      //
      let md5 = crypto.createHash("md5"); //crypto,MD5
      let password = md5.update(userPassword).digest("hex"); //
    } else {
      console.log("password err")
      res.json({
        status: "0",
        msg: "",
        result: "password-error"
      });
      return false;
    }
    console.log(password);

    let param = {
      userCreatetime: CurrentTime(),
      userName: userName,
      userPassword: password,
      userHostelArea: req.body.hostelArea,
      userHostelAddress: req.body.hostelAddress,
      userSex: req.body.sex,
      userQQ: req.body.qq,
      userState: "1"
    };
    User.create(param);
    res.json({
      status: "1",
      msg: "",
      result: "success"
    });
  } else {
    console.log("req.body error")
    res.json({
      status: "0",
      msg: "",
      result: "error"
    })
    return false;
  }
})

complete error returned:

GET /users/setSessionStorage 304 8.845 ms - -
GET /hostels 304 41.645 ms - -
{ name: "",
  pass: "123456",
  checkPass: "123456",
  hostelArea: "",
  hostelAddress: "R413",
  sex: "",
  qq: "123456" }
POST /users/register 500 26.365 ms - 2258
Error: Failed to lookup view "error" in views directory "E:\\ConvenientCampus\server\views"
    at Function.render (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\application.js:580:17)
    at ServerResponse.render (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\response.js:971:7)
    at E:\\ConvenientCampus\server\app.js:89:7
    at Layer.handle_error (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\layer.js:71:5)
    at trim_prefix (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:315:13)
    at E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:284:7
    at Function.process_params (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:335:12)
    at next (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:275:10)
    at Layer.handle_error (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\layer.js:67:12)
    at trim_prefix (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:315:13)
    at E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:284:7
    at Function.process_params (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:335:12)
    at next (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:275:10)
    at E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:635:15
    at next (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\index.js:260:14)
    at next (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\router\route.js:127:14)
userDoc err
events.js:183
      throw er; // Unhandled "error" event
      ^

Error: Can"t set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
    at ServerResponse.header (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\response.js:730:10)
    at ServerResponse.send (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\response.js:170:12)
    at ServerResponse.json (E:\\ConvenientCampus\node_modules\_express@4.15.5@express\lib\response.js:256:15)
    at E:\\ConvenientCampus\server\routes\users.js:80:13
    at E:\\ConvenientCampus\node_modules\_mongoose@5.0.9@mongoose\lib\model.js:3930:16
    at Immediate.<anonymous> (E:\\ConvenientCampus\node_modules\_mongoose@5.0.9@mongoose\lib\query.js:1514:14)
    at Immediate._onImmediate (E:\\ConvenientCampus\node_modules\_mquery@3.0.0@mquery\lib\utils.js:119:16)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)
Feb.28,2021

this error should be the logic before the request has been returned to the client.


for the same request request, you have previously called res.end () or res.json () to complete the response, so you can no longer respond.


there is something wrong with your return, and the return in the asynchronous callback will not prevent external code from executing, so the final res, will still execute and return the error of Can't set headers after they are sent

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bf747a-317df.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bf747a-317df.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?