user938363
user938363

Reputation: 10350

https Nodejs: how to check status of POST https request?

Here is snippet of POST code from Nodejs document about https module.

const https = require('https')

const data = JSON.stringify({
  todo: 'Buy the milk'
})

const options = {
  hostname: 'whatever.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`) //<<==is res.statusCode also the same as req.statusCode?

  res.on('data', d => {
    process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(error)
})

req.write(data). //upload data with POST request
//<<== check req.statusCode here???
req.end()

Here https.request returns an instance of http.ClientRequest class while res is returned with callback. If one wants to know the status of POST request, which variable shall be checked? req or res or both? BTW are req and res the same?

Upvotes: 1

Views: 1368

Answers (1)

Wodlo
Wodlo

Reputation: 937

Inside your callback function, res.statusCode should give you the status code of your POST request.

Your req variable will be a http.ClientRequest object which represents an in-progress request so you won't be able to get the status code from that.

Upvotes: 2

Related Questions