Make body default to null in Request

Fixes #208.
This commit is contained in:
Timothy Gu 2016-12-04 13:16:03 -08:00
parent 3d676235a8
commit cc4ace1778
3 changed files with 19 additions and 8 deletions

View File

@ -184,7 +184,7 @@ function fetch(url, opts) {
return;
});
// accept string, buffer or readable stream as body
// accept string, buffer, readable stream or null as body
// per spec we will call tostring on non-stream objects
if (typeof request.body === 'string') {
req.write(request.body);
@ -192,9 +192,9 @@ function fetch(url, opts) {
} else if (request.body instanceof Buffer) {
req.write(request.body);
req.end()
} else if (typeof request.body === 'object' && request.body.pipe) {
} else if (request.body && typeof request.body === 'object' && request.body.pipe) {
request.body.pipe(req);
} else if (typeof request.body === 'object') {
} else if (request.body && typeof request.body === 'object') {
req.write(request.body.toString());
req.end();
} else {

View File

@ -40,12 +40,18 @@ export default class Request extends Body {
let method = init.method || input.method || 'GET';
if ((init.body != null || input instanceof Request && input.body != null) &&
if ((init.body != null || input instanceof Request && input.body !== null) &&
(method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
super(init.body || clone(input), {
let inputBody = init.body != null ?
init.body :
input instanceof Request && input.body !== null ?
clone(input) :
null;
super(inputBody, {
timeout: init.timeout || input.timeout || 0,
size: init.size || input.size || 0
});

View File

@ -1544,9 +1544,14 @@ describe(`node-fetch with FOLLOW_SPEC = ${defaultFollowSpec}`, () => {
it('should default to null as body', function() {
const res = new Response();
expect(res.body).to.equal(null);
return res.text().then(result => {
expect(result).to.equal('');
});
const req = new Request('.');
expect(req.body).to.equal(null);
const cb = result => expect(result).to.equal('');
return Promise.all([
res.text().then(cb),
req.text().then(cb)
]);
});
it('should default to 200 as status code', function() {