From 986abbe0b2ca0e33078db114637505996fa70bd7 Mon Sep 17 00:00:00 2001 From: Dzmitry Shylovich Date: Wed, 7 Dec 2016 03:20:43 +0300 Subject: [PATCH] fix(http): set the default Accept header (#12989) Fixes #6354 --- .../@angular/http/src/backends/xhr_backend.ts | 8 ++++++-- .../http/test/backends/xhr_backend_spec.ts | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/modules/@angular/http/src/backends/xhr_backend.ts b/modules/@angular/http/src/backends/xhr_backend.ts index 7d1ee961be..ca55534f1a 100644 --- a/modules/@angular/http/src/backends/xhr_backend.ts +++ b/modules/@angular/http/src/backends/xhr_backend.ts @@ -109,9 +109,13 @@ export class XHRConnection implements Connection { this.setDetectedContentType(req, _xhr); - if (req.headers != null) { - req.headers.forEach((values, name) => _xhr.setRequestHeader(name, values.join(','))); + if (req.headers == null) { + req.headers = new Headers(); } + if (!req.headers.has('Accept')) { + req.headers.append('Accept', 'application/json, text/plain, */*'); + } + req.headers.forEach((values, name) => _xhr.setRequestHeader(name, values.join(','))); // Select the correct buffer type to store the response if (req.responseType != null && _xhr.responseType != null) { diff --git a/modules/@angular/http/test/backends/xhr_backend_spec.ts b/modules/@angular/http/test/backends/xhr_backend_spec.ts index c9a4236436..f46765ba06 100644 --- a/modules/@angular/http/test/backends/xhr_backend_spec.ts +++ b/modules/@angular/http/test/backends/xhr_backend_spec.ts @@ -237,6 +237,25 @@ export function main() { expect(setRequestHeaderSpy).toHaveBeenCalledWith('X-Multi', 'a,b'); }); + it('should attach default Accept header', () => { + const headers = new Headers(); + const base = new BaseRequestOptions(); + const connection = new XHRConnection( + new Request(base.merge(new RequestOptions({headers}))), new MockBrowserXHR()); + connection.response.subscribe(); + expect(setRequestHeaderSpy) + .toHaveBeenCalledWith('Accept', 'application/json, text/plain, */*'); + }); + + it('should not override user provided Accept header', () => { + const headers = new Headers({'Accept': 'text/xml'}); + const base = new BaseRequestOptions(); + const connection = new XHRConnection( + new Request(base.merge(new RequestOptions({headers}))), new MockBrowserXHR()); + connection.response.subscribe(); + expect(setRequestHeaderSpy).toHaveBeenCalledWith('Accept', 'text/xml'); + }); + it('should skip content type detection if custom content type header is set', () => { const headers = new Headers({'Content-Type': 'text/plain'}); const body = {test: 'val'};