feat(http): automatically set request Content-Type header based on body type
Implement the ability to provide objects as request body. The following use cases are supported: * raw objects: a JSON payload is created and the content type set to `application/json` * text: the text is used as it is and no content type header is automatically added * URLSearchParams: a form payload is created and the content type set to `application/x-www-form-urlencoded` * FormData: the object is used as it is and no content type header is automatically added * Blob: the object is used as it is and the content type set with the value of its `type` property if any * ArrayBuffer: the object is used as it is and no content type header is automatically added Closes https://github.com/angular/http/issues/69 Closes #7310
This commit is contained in:

committed by
Misko Hevery

parent
e0c83f669e
commit
0f0a8ade7c
@ -10,6 +10,7 @@ import {isPresent, isString} from '../../src/facade/lang';
|
||||
import {Observable} from 'rxjs/Observable';
|
||||
import {Observer} from 'rxjs/Observer';
|
||||
import {isSuccess, getResponseURL} from '../http_utils';
|
||||
import {ContentType} from '../enums';
|
||||
|
||||
const XSSI_PREFIX = ')]}\',\n';
|
||||
|
||||
@ -83,6 +84,8 @@ export class XHRConnection implements Connection {
|
||||
responseObserver.error(new Response(responseOptions));
|
||||
};
|
||||
|
||||
this.setDetectedContentType(req, _xhr);
|
||||
|
||||
if (isPresent(req.headers)) {
|
||||
req.headers.forEach((values, name) => _xhr.setRequestHeader(name, values.join(',')));
|
||||
}
|
||||
@ -90,7 +93,7 @@ export class XHRConnection implements Connection {
|
||||
_xhr.addEventListener('load', onLoad);
|
||||
_xhr.addEventListener('error', onError);
|
||||
|
||||
_xhr.send(this.request.text());
|
||||
_xhr.send(this.request.getBody());
|
||||
|
||||
return () => {
|
||||
_xhr.removeEventListener('load', onLoad);
|
||||
@ -99,6 +102,34 @@ export class XHRConnection implements Connection {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
setDetectedContentType(req, _xhr) {
|
||||
// Skip if a custom Content-Type header is provided
|
||||
if (isPresent(req.headers) && isPresent(req.headers['Content-Type'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the detected content type
|
||||
switch (req.contentType) {
|
||||
case ContentType.NONE:
|
||||
break;
|
||||
case ContentType.JSON:
|
||||
_xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
break;
|
||||
case ContentType.FORM:
|
||||
_xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
|
||||
break;
|
||||
case ContentType.TEXT:
|
||||
_xhr.setRequestHeader('Content-Type', 'text/plain');
|
||||
break;
|
||||
case ContentType.BLOB:
|
||||
var blob = req.blob();
|
||||
if (blob.type) {
|
||||
_xhr.setRequestHeader('Content-Type', blob.type);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
Reference in New Issue
Block a user