Skip to content

Commit 9c5c58b

Browse files
mgjmfengmk2
authored andcommitted
feat: use :authority header of http2 requests as host (#1262)
close #1174
1 parent 9146024 commit 9c5c58b

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

lib/request.js

+1
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ module.exports = {
252252
get host() {
253253
const proxy = this.app.proxy;
254254
let host = proxy && this.get('X-Forwarded-Host');
255+
if (this.req.httpVersionMajor >= 2) host = this.get(':authority');
255256
host = host || this.get('Host');
256257
if (!host) return '';
257258
return host.split(/\s*,\s*/)[0];

test/request/host.js

+33
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,39 @@ describe('req.host', () => {
1818
});
1919
});
2020

21+
describe('when less then HTTP/2', () => {
22+
it('should not use :authority header', () => {
23+
const req = request({
24+
'httpVersionMajor': 1,
25+
'httpVersion': '1.1'
26+
});
27+
req.header[':authority'] = 'foo.com:3000';
28+
req.header.host = 'bar.com:8000';
29+
assert.equal(req.host, 'bar.com:8000');
30+
});
31+
});
32+
33+
describe('when HTTP/2', () => {
34+
it('should use :authority header', () => {
35+
const req = request({
36+
'httpVersionMajor': 2,
37+
'httpVersion': '2.0'
38+
});
39+
req.header[':authority'] = 'foo.com:3000';
40+
req.header.host = 'bar.com:8000';
41+
assert.equal(req.host, 'foo.com:3000');
42+
});
43+
44+
it('should use host header as fallback', () => {
45+
const req = request({
46+
'httpVersionMajor': 2,
47+
'httpVersion': '2.0'
48+
});
49+
req.header.host = 'bar.com:8000';
50+
assert.equal(req.host, 'bar.com:8000');
51+
});
52+
});
53+
2154
describe('when X-Forwarded-Host is present', () => {
2255
describe('and proxy is not trusted', () => {
2356
it('should be ignored', () => {

0 commit comments

Comments
 (0)