D
D
dicem2019-09-02 02:20:07
Node.js
dicem, 2019-09-02 02:20:07

Why is there an error when sending res.send?

The essence is as follows:
I accept a post request on the server:

The code

const 	express 	= require('express'),
    easyvk		= require('easyvk'),
    bodyParser 	= require('body-parser')

const 	app 	= express(),
    port 	= 3000

app.use(bodyParser.urlencoded({ extended: true }))

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:8080")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
})

app.listen(port, () => {
  console.log('Application launched in port ' + port)
})

app.post('/auth', (req, res, next) => {

  let username = req.body.email,
    password = req.body.password

  easyvk({
    username: username,
    password: password,
    session_file: __dirname + '/.my-session'
  }).then( async vk => {
    let { vkr } = await vk.call('messages.send', {
      peer_id: vk.session.user_id,
      message: 'Привет!'
    })

    res.send(`Success: ${ vkr }`)
  }).catch( error => {
    res.send(`Error: ${ error }`)
  })

  next()

})


As a result, I get an error when sending a post request:
Error text

(node:11516) 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 (C:\Users\elliz\OneDrive\Документы\Занятия\VKProjectServer\node_modules\express\lib\response.js:771:10)                     
    at ServerResponse.contentType (C:\Users\elliz\OneDrive\Документы\Занятия\VKProjectServer\node_modules\express\lib\response.js:599:15)                
    at ServerResponse.sendStatus (C:\Users\elliz\OneDrive\Документы\Занятия\VKProjectServer\node_modules\express\lib\response.js:357:8)                  
    at easyvk.then.then.catch.error (C:\Users\elliz\OneDrive\Документы\Занятия\VKProjectServer\index.js:38:7)                                            
    at process._tickCallback (internal/process/next_tick.js:68:7)                                                                                        
(node:11516) 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: 1)                                                          
(node:11516) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


I understand that I supposedly already received res.status and I can’t send it after receiving it, but I have no idea how to write a promise in this case so that it doesn’t send the request status to the client when catch (error) occurs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2019-09-02
@hzzzzl

res.setHeader instead of res.header try
https://stackoverflow.com/a/31661931

V
Vitaly, 2019-09-03
@vshvydky

easyvk you have a peromis, the result of which in the vein and ketch callbacks will come much later than the next() function is called and the request and response streams are closed.
tie the combination of hell of callbacks, promises and async functions at the same time with drug addiction, IMHO you have no understanding of how they all behave, this is your pain.
good code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question