简体   繁体   中英

Record is getting updated but I am still getting this error in console

So I am trying to update the existing records in the MongoDB and records update are being reflected correctly, but in the console, I still see these warnings and errors:

{"name":"Bruce","number":"22222","date":"2020-12-18T20:08:45.446Z","id":"5fdd0c4d72a07e5d0c63c056"}
****  { _id: 5fdd0c4d72a07e5d0c63c056,
  name: 'Bruce',
  number: '22222',
  date: 2020-12-19T06:29:29.022Z,
  __v: 0 }
// ^------- this is the record body sent from the frontend and it's being updated correctly.

// but I still get this following  errors:

error:  Error [ERR_HTTP_HEADERS_SENT]
PUT /api/persons/5fdd0c4d72a07e5d0c63c056 402 99 - 116.533 ms {"name":"Bruce","number":"22222","date":"2020-12-18T20:08:45.446Z","id":"5fdd0c4d72a07e5d0c63c056"}
(node:8288) 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 (E:\fsopen_revision\phonebook\server\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (E:\fsopen_revision\phonebook\server\node_modules\express\lib\response.js:170:12)
    at Contact.findByIdAndUpdate.then.catch (E:\fsopen_revision\phonebook\server\index.js:136:11)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:8288) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a 
catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Code is used to perform Update:


app.put("/api/persons/:id", (req, res) => {
  console.log(JSON.stringify(req.body));
  const id = Object(req.params.id);
  const body = req.body;

  const newPerson = {
    name: body.name,
    number: body.number,
    date: new Date(),
  };

  Contact.findByIdAndUpdate(id, newPerson, {
    new: true,
  })
    .then((updatedContact) => {
      console.log("**** ", updatedContact);
      return res.json(updatedContact).send({ message: "Updated" });
    })
    .catch((e) => {
      console.log("error: ", e.name);
      res.send(402).json({ name: e.name });
    });
});

The frontend is working fine and data is also being updated correctly:

在此处输入图像描述

Try this sintax, first check if user id exists in DB, then findByIdAndUpdate with error and response handling:

 updateUser: (req, res) => { const id = Object(req.params.id); const body = req.body; const newPerson = { name: body.name, number: body.number, date: new Date(), }; Contact.findById(id, (err, res) => { if(err) return res.status(500).send({message: 'Error finding user'}); }); User.findByIdAndUpdate(id, newPerson, {new: true}, (err, updatedContact) => { if(err) return res.status(500).send({message: 'Error updating'}); if(.userUpdated) return res.status(404):send({message; 'user doesnt exists'}). return res.status(200):send(contact; updatedContact); }); }

Your error message says: Cannot set headers after they are sent to the client

You can't send response two times. Either use json() method or send() method. Each of them construct headers for the response, send body (payload) and then ends sending response from the server.

// incorrect use of express api
res.json(updatedContact).send({ message: "Updated" });

// change to
res.json({ message: "Updated", contact: updatedContact });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM