-1

I have to call an api, for which we are using request library.

const options = {
    uri: 'https://abcd.com',
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer xxxxxxxxx'
    },
    form: {
        'a':1,
        'b':2
    }
}

request(options, (e, res, data) => {});

How would I rewrite the same using node's https library.

I tried using https library's https.request() with 'POST' type and .write with form object. Didn't work. Also changed Content-Type to application/x-www-form-urlencoded, didn't work either

Divyansh Singh
  • 390
  • 4
  • 16

2 Answers2

0

You can read the API docs at: https://nodejs.org/api/https.html

Below code should work fine:

const https = require('https')

const data = JSON.stringify({
        'a':1,
        'b':2
    })

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
    'Content-Length': data.length
    'Authorization': 'Bearer xxxxxxxxx'
  }
}

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)

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

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

req.write(data)
req.end()
Abhas Tandon
  • 1,859
  • 16
  • 26
  • I tried it, but didn't work. It's quite weird though. – Divyansh Singh Apr 17 '19 at 10:42
  • It's not the error. It's my client's API. so when am doing this, it's not working but if I do the same with request library using form, it works :/ It's quite weird and am very confused regarding this, so please bare with me. – Divyansh Singh Apr 17 '19 at 10:58
  • Are you able to get this API to work in Postman (getpostman.com)? If yes, just click on `code` button (right side below send button). Select nodejs - > native – Abhas Tandon Apr 17 '19 at 11:02
  • Not working. I've tried by sending the object in body, form-data. – Divyansh Singh Apr 17 '19 at 11:16
  • So it doesn't work with both postman & https module but works with request module with the code given above? – Abhas Tandon Apr 17 '19 at 11:17
0

This example is from the documentation using the request package ,the form takes a object consisting of key value pair from that of the form

request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}}, 
function(err,httpResponse,body){ /* ... */ })

enter link description here