x-http-client
Version:
An http client to make it easier to send requests (including JSONP requests) to the server.
40 lines (34 loc) • 1.13 kB
JavaScript
var merge = require('x-common-utils/merge');
var isPlainObject = require('x-common-utils/isPlainObject');
var hasOwn = require('../shared/hasOwn');
/**
* The function to set the request headers.
*
* 1. Merge the `options.noCacheHeaders` if needed.
* 2. Set the request headers if needed.
*
* @param {XMLHttpReqeust} xhr The instance of `XMLHttpReqeust`.
* @param {RequestOption} options The request options.
*/
function handleHeaders(xhr, options) {
var name;
var value;
var headers = isPlainObject(options.headers) ? options.headers : {};
if (options.noCache) {
if (isPlainObject(options.noCacheHeaders)) {
headers = merge(headers, options.noCacheHeaders);
}
}
for (name in headers) {
if (hasOwn.call(headers, name)) {
value = headers[name];
// Only the non-undefined and non-null headers are set
if (value !== undefined && value !== null) {
xhr.setRequestHeader(name, value);
}
}
}
// Set the headers back.
options.headers = headers;
}
module.exports = handleHeaders;