Fix custom Host header with arbitrary case (#430)

Regression since 1592ca1148.

Fixes: #416
Fixes: #425
This commit is contained in:
Timothy Gu 2018-03-22 22:01:45 -07:00 committed by GitHub
parent c012c4116b
commit 8aac53679d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 35 additions and 7 deletions

View File

@ -323,6 +323,25 @@ Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
configurable: true
});
/**
* Export the Headers object in a form that Node.js can consume.
*
* @param Headers headers
* @return Object
*/
export function exportNodeCompatibleHeaders(headers) {
const obj = Object.assign({ __proto__: null }, headers[MAP]);
// http.request() only supports string as Host header. This hack makes
// specifying custom Host header possible.
const hostHeaderKey = find(headers[MAP], 'Host');
if (hostHeaderKey !== undefined) {
obj[hostHeaderKey] = obj[hostHeaderKey][0];
}
return obj;
}
/**
* Create a Headers object from an object of headers, ignoring those that do
* not conform to HTTP grammar productions.

View File

@ -43,11 +43,6 @@ export default function fetch(url, opts) {
const send = (options.protocol === 'https:' ? https : http).request;
// http.request only support string as host header, this hack make custom host header possible
if (options.headers.host) {
options.headers.host = options.headers.host[0];
}
// send request
const req = send(options);
let reqTimeout;

View File

@ -7,7 +7,7 @@
* All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
*/
import Headers from './headers.js';
import Headers, { exportNodeCompatibleHeaders } from './headers.js';
import Body, { clone, extractContentType, getTotalBytes } from './body';
const { format: format_url, parse: parse_url } = require('url');
@ -200,7 +200,7 @@ export function getNodeRequestOptions(request) {
return Object.assign({}, parsedURL, {
method: request.method,
headers: headers.raw(),
headers: exportNodeCompatibleHeaders(headers),
agent: request.agent
});
}

View File

@ -208,6 +208,20 @@ describe('node-fetch', () => {
});
});
it('should accept custom HoSt header', function() {
const url = `${base}inspect`;
const opts = {
headers: {
HoSt: 'example.com'
}
};
return fetch(url, opts).then(res => {
return res.json();
}).then(res => {
expect(res.headers['host']).to.equal('example.com');
});
});
it('should follow redirect code 301', function() {
const url = `${base}redirect/301`;
return fetch(url).then(res => {