From 54778a6f0b105153e62cd042c502c39508e12a99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fredrik=20Bostr=C3=B6m?= Date: Wed, 9 May 2018 14:01:08 +0300 Subject: [PATCH] Parse data as JSON when content type is application/json --- lib/najax.js | 2 +- test/test-najax.js | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/najax.js b/lib/najax.js index 958816d..6d83bda 100644 --- a/lib/najax.js +++ b/lib/najax.js @@ -144,7 +144,7 @@ function najax (uri, options, callback) { jqXHR.readyState = statusCode > 0 ? 4 : 0 jqXHR.status = statusCode - if (o.dataType === 'json' || o.dataType === 'jsonp') { + if (o.dataType === 'json' || o.dataType === 'jsonp' || (res.headers['content-type'] || '').startsWith('application/json')) { // replace control characters try { data = JSON.parse(data.replace(/[\cA-\cZ]/gi, '')) diff --git a/test/test-najax.js b/test/test-najax.js index 1bfc7a2..92592f7 100644 --- a/test/test-najax.js +++ b/test/test-najax.js @@ -304,6 +304,21 @@ describe('data', function (next) { } }, createSuccess(done)) }) + + it('should parse the response as json if the response content-type is application/json', function(done) { + nock('http://www.example.com') + .get('/') + .reply(200, {some: 'json'}, { + 'Content-Type': 'application/json; charset=utf-8' + }) + + najax.get('http://www.example.com', function (data, statusText) { + expect(data.some).to.equal('json') + expect(statusText).to.equal('success') + done() + }) + + }) }) describe('timeout', function () {