2

I am new to this topic of Rest Apis, and I was creating a simple one where I receive a json with movie data and give a small response. As I am new I want to start with what would be the logic and it is an array that is saving data.

But when I send data through PostMan, it saves everything well and does its job, but I get this error on the console.

someone who can guide me please

MY CODE

router.post('/', (req, res) => {
    const {titulo, director, year, rating} = req.body;
    if (titulo && director && year && rating) {
        const id = movies.length + 1;
        const newMovie = {...req.body, id};
        movies.push(newMovie);
        res.json(movies);
    } else {
        res.status(500).json({error: 'Ha Ocurrido un error'});
    }
    res.send('recibido');
});

module.exports = router;

CMD ERROR

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:\Users\ManuelLeigh\Desktop\restapi\node_modules\express\lib\response.js:776:10)
    at ServerResponse.send (C:\Users\ManuelLeigh\Desktop\restapi\node_modules\express\lib\response.js:170:12)
    at C:\Users\ManuelLeigh\Desktop\restapi\src\routes\movies.js:20:9
    at Layer.handle [as handle_request] (C:\Users\ManuelLeigh\Desktop\restapi\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\ManuelLeigh\Desktop\restapi\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\ManuelLeigh\Desktop\restapi\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\ManuelLeigh\Desktop\restapi\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\ManuelLeigh\Desktop\restapi\node_modules\express\lib\router\index.js:281:22

Postman Header:

Content-Type: application/json
Manuel Leigh
  • 25
  • 1
  • 1
  • 5

5 Answers5

8

Your code is trying to send response after it is sent. Check for following lines, in if and else,, you are already sending response to server and after this is processed, on last line, you are sending some text.

   if (titulo && director && year && rating) {
        res.json(movies);
    } else {
        res.status(500).json({error: 'Ha Ocurrido un error'});
    }
    res.send('recibido');

Update your code as below,

router.post('/', (req, res) => {
    const {titulo, director, year, rating} = req.body;
    if (titulo && director && year && rating) {
        const id = movies.length + 1;
        const newMovie = {...req.body, id};
        movies.push(newMovie);
        res.json(movies);
    } else {
        res.status(500).json({error: 'Ha Ocurrido un error'});
    }
   // res.send('recibido');
});

module.exports = router;
Vikas Keskar
  • 1,158
  • 9
  • 17
3

after if-else block, you again try to send response.By putting return after sending response in each block, you can fix your problem or other simple way, just comment res.send("recibido"). simple way is to just comment res.send("recibido")

you can write your code this way:

router.post('/', (req, res) => {
const {titulo, director, year, rating} = req.body;
if (titulo && director && year && rating) {
    const id = movies.length + 1;
    const newMovie = {...req.body, id};
    movies.push(newMovie);
    res.json(movies);      
} else {
    res.status(500).json({error: 'Ha Ocurrido un error'});        
}
   // res.send('recibido');
});

module.exports = router;
Ramin Khodaie
  • 242
  • 3
  • 10
2

Use return statement for res.json, res.status and res.send provided the if else logic is what you want.

I was encountering the above error in my code only to realise wherever I had a logic statement, for some conditions the code kept on running and needed to return the outcome e.g return res.status(400).send("Error Message)

Chief
  • 854
  • 12
  • 27
  • Yes this worked for me too! Could you please format your answer into a code with an example, it would be better to get an idea at first glimpse. I was also trying to put middleware functions and validation checks with lots of if & else statement, and wasn't returning. – Clinto_92_Abraham May 17 '23 at 06:50
0

I found the answer to my error by putting a return, but I don't know how correct this solution is

const isAdmin = async (req, res, next) => {
  if (req.isAuthenticated() && req.user.role === "admin") {
    return next()
  } else {
    req.flash("danger", "not allowed")
    res.redirect("/")
  }
  return next()
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

For me I used async/await for request and response handler to getover the error. it's something like this:

router.post("/", async (req,res)=>{
   await myFunc(val1,val2).then(()=>{
    res.send("success")
   )
   .catch((err)=>{
    res.send(err)
   )
})
Bahaa Salaheldin
  • 515
  • 1
  • 7
  • 16