diff --git a/fetch.js b/fetch.js index f39a983a..1da531b3 100644 --- a/fetch.js +++ b/fetch.js @@ -499,6 +499,19 @@ Response.error = function() { return response } +Response.json = function(data, options) { + var responseInit = options ? { + headers: new Headers(options.headers), + status: options.status, + statusText: options.statusText + } : { + headers: new Headers() + } + responseInit.headers.set("content-type", "application/json") + + return new Response(JSON.stringify(data), responseInit) +} + var redirectStatuses = [301, 302, 303, 307, 308] Response.redirect = function(url, status) { diff --git a/test/test.js b/test/test.js index ce0007c0..ea62ed69 100644 --- a/test/test.js +++ b/test/test.js @@ -702,6 +702,26 @@ exercise.forEach(function(exerciseMode) { assert.equal(r.type, 'error') }) + test('json creates json Response with ResponseInit', function() { + var r = Response.json({key: "value"}, { + headers: new Headers('header', 'value'), + status: 404, + statusText: "NOT FOUND" + }) + assert(r instanceof Response) + assert.equal(r.headers.get('content-type'), 'application/json') + assert.equal(r.status, 404) + assert.equal(r.statusText, "NOT FOUND") + }) + + test('json creates json Response without ResponseInit', function() { + var r = Response.json({key: "value"}) + assert(r instanceof Response) + assert.equal(r.headers.get('content-type'), 'application/json') + assert.equal(r.status, 200) + assert.equal(r.statusText, '') + }) + test('redirect creates redirect Response', function() { var r = Response.redirect('https://fetch.spec.whatwg.org/', 301) assert(r instanceof Response)