Axios set Content-Length manually, nodeJS
Solution 1
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:
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()
Solution 2
I can't add a comment because of low reputation, but part of Sandeep Patel's answer regarding Axios
is outdated. You can set Content-Length
manually. Axios
will not override Content-Length
if content-length
header is present:
// Add Content-Length header if data exists
if (!headerNames['content-length']) {
headers['Content-Length'] = data.length;
}
Source: https://github.com/axios/axios/blob/master/lib/adapters/http.js#L112-L116
So in your case it would be:
let data = `Some text data...`;
let form = await Axios.post(
"url...",
data,
{
headers: {
Authentication: "token....",
"Content-Type": "contentType...",
//set content-length manually
"Content-Length": "268",
"content-length": "268"
}
}
).catch(e => e);
Shmili Breuer
Updated on November 26, 2022Comments
-
Shmili Breuer over 1 year
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.
-
Ashish Modi over 4 yearswhy do you need to do that? this setting is populated automattically.
-
Shmili Breuer over 4 years@Ashish Modi I was having issues and was trying to debug, I actually solved my issue without setting the content-length manually.
-
Ashish Modi over 4 yearsthis is what
got
doc'n says - The content-length header will be automatically set if body is a string / Buffer / fs.createReadStream instance / form-data instance, and content-length and transfer-encoding are not manually set in options.headers.
-