From 2d3707dfa7e5eac0abf5bc3b36de6bb99f3afffb Mon Sep 17 00:00:00 2001 From: Dan Hardman Date: Thu, 24 Mar 2016 17:50:53 +0000 Subject: [PATCH] Encode request data as JSON when Content-Type is set to application/json --- src/reqwest.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/reqwest.js b/src/reqwest.js index fbc85e0..3c9366b 100644 --- a/src/reqwest.js +++ b/src/reqwest.js @@ -196,12 +196,22 @@ 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') - ? reqwest.toQueryString(o['data']) - : (o['data'] || null) , http - , sendWait = false + , sendWait = false; + + // convert JSON objects to JSON strings when contentType is application/json + // and other non-string objects to query-string form unless o['processData'] + // is false + var data = null; + if (o['processData'] !== false && o['data']) { + if (o['contentType'] === 'application/json' && typeof o['data'] === 'object') { + data = JSON.stringify(o['data']); + } else if (typeof o['data'] !== 'string')) { + data = reqwest.toQueryString(o['data']); + } else { + data = o['data']; + } + } // if we're working on a GET request and we have data then we should append // query string to end of URL and not post data