0

This is the post request I tried to create for login

router.post('/login', async(req, res) =>{

const user =  await User.findOne({gmail: req.body.gmail})
!user && res.status(404).json("user not matched")

const p = await bcrypt.compare(req.body.password, user.password)
!p && res.status(400).json("password not matched") 

res.status(200).json(user)
}   

)

When I click the send button in postman I get this response with the following error: enter image description here

This is the error I get when I "send" a post request in postman:

::1 - - [19/Jan/2022:11:48:06 +0000] "POST /api/auth/login HTTP/1.1" 200 22 node:internal/errors:464 ErrorCaptureStackTrace(err); ^

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 (D:\Projects\social\node_modules\express\lib\response.js:776:10) at ServerResponse.send (D:\Projects\social\node_modules\express\lib\response.js:170:12) at ServerResponse.json (D:\Projects\social\node_modules\express\lib\response.js:267:15) at D:\Projects\social\routes\auth.js:28:21 { code: 'ERR_HTTP_HEADERS_SENT' } [nodemon] app crashed - waiting for file changes before starting...

after I click the "send" button second time, the response shows this enter image description here

what did I do wrong here?

Saken Rai
  • 19
  • 3
  • 3
    The first thing you did wrong is not google this very common error before posting here. The error means you're trying to send two or more replies. Drop that weird coding style and do `if (!user) return res.status(404).json("user not matched")` instead so express doesn't call res.send() multiple times. –  Jan 19 '22 at 12:04
  • 2
    Duplicate: [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) –  Jan 19 '22 at 12:06

1 Answers1

0

This is a very common error and is spread across the internet. You're trying to send 2 responses. When your check on the line 5 succeeds - you send a response, then your code continues and reaches the line 7 where you're sending a response as well. Just wrap them inside an if-else block to prevent multiple responses.

David Gabrielyan
  • 227
  • 2
  • 12