Split Content-Type extraction to Request and Body
It is done in this way in the spec.
This commit is contained in:
parent
d3071fa46a
commit
0285828fb8
20
src/body.js
20
src/body.js
|
@ -249,5 +249,25 @@ export function clone(instance) {
|
|||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the operation "extract a `Content-Type` value from |object|" as
|
||||
* specified in the specification:
|
||||
* https://fetch.spec.whatwg.org/#concept-bodyinit-extract
|
||||
*
|
||||
* This function assumes that instance.body is present and non-null.
|
||||
*
|
||||
* @param Mixed instance Response or Request instance
|
||||
*/
|
||||
export function extractContentType(instance) {
|
||||
// detect form data input from form-data module
|
||||
if (typeof instance.body.getBoundary === 'function') {
|
||||
return `multipart/form-data;boundary=${instance.body.getBoundary()}`;
|
||||
}
|
||||
|
||||
if (typeof instance.body === 'string') {
|
||||
return 'text/plain;charset=UTF-8';
|
||||
}
|
||||
}
|
||||
|
||||
// expose Promise
|
||||
Body.Promise = global.Promise;
|
||||
|
|
|
@ -68,11 +68,6 @@ function fetch(url, opts) {
|
|||
headers.set('accept', '*/*');
|
||||
}
|
||||
|
||||
// detect form data input from form-data module, this hack avoid the need to pass multipart header manually
|
||||
if (!headers.has('content-type') && options.body && typeof options.body.getBoundary === 'function') {
|
||||
headers.set('content-type', `multipart/form-data; boundary=${options.body.getBoundary()}`);
|
||||
}
|
||||
|
||||
// bring node-fetch closer to browser behavior by setting content-length automatically
|
||||
if (!headers.has('content-length') && /post|put|patch|delete/i.test(options.method)) {
|
||||
if (typeof options.body === 'string') {
|
||||
|
|
|
@ -7,7 +7,7 @@
|
|||
|
||||
import { format as format_url, parse as parse_url } from 'url';
|
||||
import Headers from './headers.js';
|
||||
import Body, { clone } from './body';
|
||||
import Body, { clone, extractContentType } from './body';
|
||||
|
||||
/**
|
||||
* Request class
|
||||
|
@ -46,6 +46,13 @@ export default class Request extends Body {
|
|||
this.redirect = init.redirect || input.redirect || 'follow';
|
||||
this.headers = new Headers(init.headers || input.headers || {});
|
||||
|
||||
if (init.body) {
|
||||
const contentType = extractContentType(this);
|
||||
if (contentType && !this.headers.has('Content-Type')) {
|
||||
this.headers.append('Content-Type', contentType);
|
||||
}
|
||||
}
|
||||
|
||||
// server only options
|
||||
this.follow = init.follow !== undefined ?
|
||||
init.follow : input.follow !== undefined ?
|
||||
|
|
Loading…
Reference in New Issue