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

Suggestion: add JSON.stringify to post if data is a JSON object and contentType is 'application/json' #255

Open
rw3iss opened this issue Sep 29, 2016 · 0 comments

Comments

@rw3iss
Copy link

rw3iss commented Sep 29, 2016

Currently, if a json object is sent as data, it will url-encode the object.
If the server expects JSON, this will kill the request.
Reqwest includes the option to 'processData = false' within the request, but this leaves a JSON object being sent as [object Object].
This should be especially true of the contentType property is set to application/json, otherwise why would we send a url-encoded value if we are telling it to send json?

It would be nice to add an option to stringify a json object instead of url-encoding it, or otherwise auto-detect the application/json contentType and stringify the json object.

I added this in the code (without the option, just an object and contentType check),
in reqwest.js, line 203 inside getRequest():

  function getRequest(fn, err) {
    var o = this.o
      , method = (o['method'] || 'GET').toUpperCase()
      , url = typeof o === 'string' ? o : o['url']
      // convert non-string objects to query-string form unless o['processData'] is false
      , data = (o['processData'] !== false && o['data'] && typeof o['data'] !== 'string')
        ? (typeof o['data'] == 'object' && o['contentType'] == 'application/json') ? JSON.stringify(o['data']) : reqwest.toQueryString(o['data'])
        : (o['data'] || null)
      , http
      , sendWait = false

    ...

If anyone doesn't see an objection to this, I'll add it as a pull request.

@rw3iss rw3iss changed the title Suggestion: add JSON.stringify to post if data is a JSON object Suggestion: add JSON.stringify to post if data is a JSON object and contentType is 'application/json' Sep 29, 2016
mockdeep added a commit to mockdeep/questlog that referenced this issue Jul 9, 2017
reqwest hasn't been updated in 2 years and I encountered a bug where
json data still gets serialized as params in url format, so decided to
roll my own based on the `fetch` API. Took some work figuring out edge
cases and whatnot, but here we are.

ded/reqwest#255

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
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