Bug: Accept header is not sent when using basic authorization
rudolfbyker opened this issue · 0 comments
rudolfbyker commented
In the getJSON
function, which currently looks like this
function getJSON(params, callback) {
let headers = {
accept: 'application/json; charset=utf-8',
};
let options = {
host: params.host,
port: params.port,
path: params.fullPath,
headers: headers,
family: params.ipVersion,
};
if (params.request) {
options = Object.assign(options, params.request);
}
if (params.agent !== undefined) {
options.agent = params.agent;
}
if (params.authorization) {
headers = {
authorization: params.authorization,
};
options.headers = headers;
}
const request = pickProtocol(params.secure).get(options);
request.on('response', handleJSONResponse(request, params.bigint, callback));
request.on('error', function (err) {
if (callback) callback(err, null);
});
return request;
}
the accept header is thrown away if params.authorization
contains something. To make this clearer, here is an equivalent, refactored version:
function getJSON(params, callback) {
let options = {
host: params.host,
port: params.port,
path: params.fullPath,
headers: {
accept: 'application/json; charset=utf-8',
},
family: params.ipVersion,
};
if (params.request) {
options = Object.assign(options, params.request);
}
if (params.agent !== undefined) {
options.agent = params.agent;
}
if (params.authorization) {
// Previous values for options.headers are not considered.
options.headers = {
authorization: params.authorization,
};
}
const request = pickProtocol(params.secure).get(options);
request.on('response', handleJSONResponse(request, params.bigint, callback));
request.on('error', function (err) {
if (callback) callback(err, null);
});
return request;
}
A quick fix would be to change this
if (params.authorization) {
options.headers = {
authorization: params.authorization,
};
}
into this
if (params.authorization) {
options.headers.authorization = params.authorization;
}
But it looks like the whole getJSON
function is actually a bit clunky and can be rewritten much neater. There is a lot of unnecessary juggling of params
and options
between getJSON
and Client.prototype.get
, which is the only place it is used. But I'll leave that for a future issue :)