0

I am new to Nodejs and want to send response code 404 when the file mimetype is not png or jpeg. As well as I want to send response code 404 if the file size is greater than 5mb.

I am doing it with this code and I am getting this error in the log on nodejs.

enter image description here

router.post("/insertNewProduct", auth, receive.single('productUrl'), async (req, res) => {
    try {
      
        if (req.file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
            res.status(404).send({
              
                message: "Column productUrl can only accept jpeg or png image",
                data: {}
            })
        } else if (req.file.size > (1024 * 1024 * 5)) {
            res.status(404).send({
                message: "Image size can not be greater that 5mb.",
                data: {}
            })
        }else{
              //Add Product to db
       }

 } catch (e) {
        res.status(404).send({
            message: e,
            data: {}
        });
    }
});
Archit Sandesara
  • 605
  • 1
  • 12
  • 25
  • 3
    `return res.send()` – Andreas Schrottenbaum Nov 13 '20 at 13:28
  • Adding return removes the error but the message is blank in the response when the `if (req.file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') { res.status(404).send({ message: "Column productUrl can only accept jpeg or png image", data: {} }) } ` condition is true. – Archit Sandesara Nov 13 '20 at 13:33
  • `{ "message": {}, "data": {} }` – Archit Sandesara Nov 13 '20 at 13:34
  • 1
    To send back an object, use `res.json()` (also, the cause of the error, which has lots of existing answers, is that you're trying to send back a response multiple times, so you need to make sure that only a single. res.send() is called) –  Nov 13 '20 at 13:40
  • Does this answer your question? [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – Mika Sundland Nov 13 '20 at 14:55
  • 1
    Adding return before res.send() solved the issue as suggested by @AndreasSchrottenbaum. – Archit Sandesara Nov 17 '20 at 18:42

0 Answers0