Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

fix($http) No error for json-like repsonses without "application/json" content-type #16075

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/ng/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,15 @@ function defaultHttpResponseTransform(data, headers) {

if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0);

if (hasJsonContentType || isJsonLike(tempData)) {
try {
data = fromJson(tempData);
} catch (e) {
if (!hasJsonContentType) {
return data;
}
throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
'Parse error: "{1}"', data, e);
}
Expand Down
39 changes: 38 additions & 1 deletion test/ng/httpSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1380,8 +1380,45 @@ describe('$http', function() {
expect(errCallback.calls.mostRecent().args[0]).toEqualMinErr('$http', 'baddata');
});

});
it('should not throw an error if JSON is invalid but content-type is not application/json', function() {
$httpBackend.expect('GET', '/url').respond('{abcd}', {'Content-Type': 'text/plain'});

$http.get('/url').then(callback);
$httpBackend.flush();

expect(callback).toHaveBeenCalledOnce();
});

it('should not throw an error if JSON is invalid but content-type is not specified', function() {
$httpBackend.expect('GET', '/url').respond('{abcd}');

$http.get('/url').then(callback);
$httpBackend.flush();

expect(callback).toHaveBeenCalledOnce();
});

it('should return response unprocessed if JSON is invalid but content-type is not application/json', function() {
var response = '{abcd}';
$httpBackend.expect('GET', '/url').respond(response, {'Content-Type': 'text/plain'});

$http.get('/url').then(callback);
$httpBackend.flush();

expect(callback.calls.mostRecent().args[0].data).toBe(response);
});

it('should return response unprocessed if JSON is invalid but content-type is not specified', function() {
var response = '{abcd}';
$httpBackend.expect('GET', '/url').respond(response);

$http.get('/url').then(callback);
$httpBackend.flush();

expect(callback.calls.mostRecent().args[0].data).toBe(response);
});

});

it('should have access to response headers', function() {
$httpBackend.expect('GET', '/url').respond(200, 'response', {h1: 'header1'});
Expand Down