Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why does Axios trims JSON bodies? #4892

Closed
valeriangalliat opened this issue Jul 27, 2022 · 1 comment
Closed

Why does Axios trims JSON bodies? #4892

valeriangalliat opened this issue Jul 27, 2022 · 1 comment

Comments

@valeriangalliat
Copy link

Describe the issue

When the Content-Type is set to application/json, and when given an already stringified JSON data parameter, Axios trims the body.

This can be an issue e.g. when computing cryptographic signatures or hashes of the body: the signature of the data parameter we give Axios won't match the one for the payload received on the server side.

Example Code

require('http').createServer((req, res) => {
  process.stdout.write('BEFORE:')
  req.pipe(process.stdout)
  req.on('end', () => process.stdout.write(':AFTER'))
  res.end()
}).listen(9876)

require('axios')({
  method: 'POST',
  url: 'http://localhost:9876/',
  headers: {
    'content-type': 'application/json',
  },
  data: '   {\n  "foo":       "bar"\n\n    }   '
})

Expected behavior, if applicable

The server should log the unaltered body - with the before/after flags above:

BEFORE:   {
  "foo":       "bar"

    }   :AFTER

Instead, Axios trims the body, resulting in the server logging:

BEFORE:{
  "foo":       "bar"

    }:AFTER

Environment

  • Axios Version 0.27.2
  • Adapter HTTP
  • Node.js Version 18.6.0
  • OS: OSX 12.4

Additional notes

This happens because the stringifySafely function (which is called on application/json bodies) explicitly trims an already-stringified JSON body:

return utils.trim(rawValue);

It seems this comes from this PR #4020 but I don't find any explanation why trim was added there. If anybody knows the reason, I'd be curious to know! Otherwise I can submit a patch to remove the trim but I'm worried that might break other code relying on the trim to happen...

Otherwise I'm wondering how I could send an application/json request without running in this special case of preprocessing the data parameter - in a way where I can give a raw data string that is guaranteed to be sent unaltered. Thanks for the help!

@valeriangalliat
Copy link
Author

It looks like I can bypass this body preprocessing behaviour by passing a stream or buffer instead of a string.

Even though I'm unclear why the trim happened in the first place, I'll close this issue. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant