Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Automatically decode JSON responses based on Content-type #339

Closed
wants to merge 1 commit into from

3 participants

@nylen
Owner

This change addresses a shortcoming of the current JSON handling: it doesn't seem to be possible to send a non-JSON request while accepting a JSON response, or vice-versa. I've made it so that responses will always be parsed as JSON if the response Content-type header is application/json.

Do we need more options here? Should I try to rework the JSON handling further?

@mikeal
Owner

this is a breaking change. this behavior is already the case if you do request({json:true}), adding this will essentially change that default, which I don't think I agree with.

@aseemk

@mikeal: is this something you'd consider for request 3.x?

@mikeal
Owner

nope, i don't think this is behavior can be assumed. even in cases where i'm going to decode the JSON i often want the string to decode myself. when i do want to decode the json {json:true} can be passed. i also don't want to open up the flood gates to other decoding options on the body.

@mikeal mikeal closed this
@nylen
Owner

I still have an issue with the current handling:

it doesn't seem to be possible to send a non-JSON request while accepting a JSON response, or vice-versa.

I think the json handling should be more flexible to accommodate cases like this. I'm willing to help if you agree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 6 additions and 1 deletion.
  1. +6 −1 main.js
View
7 main.js
@@ -650,8 +650,13 @@ Request.prototype.start = function () {
try {
response.body = JSON.parse(response.body)
} catch (e) {}
+ } else if (response.headers && response.headers['content-type']) {
+ var contentType = response.headers['content-type'].split(';')[0]
+ if (contentType == 'application/json') {
+ response.body = JSON.parse(response.body)
+ }
}
-
+
self.emit('complete', response, response.body)
})
}
Something went wrong with that request. Please try again.