Skip to content
Open
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
13 changes: 13 additions & 0 deletions fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
20 changes: 20 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down