Axios set Content-Length manually, nodeJS

Shmili Breuer picture Shmili Breuer · Jan 28, 2020 · Viewed 9.2k times · Source

Is there a way to send a post request in nodeJS and specify th content-length.

I tried (using axios):

let data = `Some text data...........`;

let form = await Axios.post(
    "url.......",
    data,
    {
        headers: {
            Authentication: "token.....",
            "Content-Type": "multipart/form-data; boundary=c9236fb18bed42c49590f58f8cc327e3",
            //set content-length manually 
            "Content-Length": "268"
        }
    }
).catch(e => e);

It doesn't work, the length is set automatically to a value other then the one I pass.

I am using axios but open to using any other way to post from nodeJS.

Answer

Sandeep Patel picture Sandeep Patel · Jan 28, 2020

In Axios, If data is present it will set length calculated from data, so even if you pass header content-length, it will be overridden by code: enter image description here

Check this out for more details: https://github.com/axios/axios/blob/master/lib/adapters/http.js

Using http or https module you can do:

const https = require('https')

const data = JSON.stringify({
  key:values
})

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/testpath',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}
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()