简体   繁体   中英

HTTP Content-Length header calculation in javascript

I am new in javascript and node.js. I have an issue in calling a rest endpoint. My problem is when I try to call the endpoint using Postman everything is ok. I can see the calculated Content-Length header in Postman console. But when I try to call the same endpoint in javascript something is wrong because the calculated Content-Length is a bit lower than the calculated one by Postman. Here is my node.js code that I am using to call the endpoint. Note that the API is multipart API that is used for uploading the files.

file = fs.readFileSync('/Users/.../Documents/doc.pdf')
form = new FormData()
form.append('file', file)
headers = Object.assign({'Content-Length': form.getLengthSync() }, form.getHeaders())
config = {
    method: 'post',
    url: 'https://staging:...',
    headers: headers,
    data : form
};
axios(config).then((res) ->
        console.log("The file is posted successfully. status is : " + res.status)
    ).catch((err) -> 
        console.log("The error occurred in posting file : " + err)
    )

Can you please tell me what is missing here? for example for a specific file that I am testing the postman calculated value is 388 but the code calculated it as 379 for the same file. Note: when I hardcode the value with the value from Postman everything is ok.

Issue #426 in the form-data repository seems to describe a solution for your problem.

I gave it a try locally and managed to get the desired results by applying what described in the issue:

const filePath = '/Users/.../Documents/doc.pdf';
const form = new FormData();
let options = {
  knownLength: fs.statSync(filePath).size
}
form.append(
  'file',
  fs.createReadStream(filePath),
  options,
);

I gather the issue is related to the acclaration made in the getLengthSync specification , which states that stream lengths' aren't calculated, hence the extra step that must be taken in order to provide the correct file length to the FormData instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM