-
Notifications
You must be signed in to change notification settings - Fork 4
/
redirect.js
86 lines (70 loc) · 2.09 KB
/
redirect.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var url = require('url')
var error = require('../utils/error')
module.exports = (args, client) => ({options, res, body, raw}) => {
if (!/^3/.test(res.statusCode)) {
// not a redirect
return {options, res, body, raw}
}
var defaults = {
max: 3,
all: false,
method: true,
referer: false,
auth: true,
followed: 0,
hostname: options.hostname,
}
var redirect = Object.assign(defaults, args.redirect)
var header = Object.keys(res.headers)
.find((name) => name.toLowerCase() === 'location')
var location = res.headers[header]
if (!location || (!redirect.all && /patch|put|post|delete/i.test(options.method))) {
// do not follow redirects
return {options, res, body, raw}
}
// relative location
if (!/^https?:/.test(location)) {
location = url.resolve(
options.protocol + '//' + options.hostname +
(options.port && options.port !== 80 ? `:${options.port}` : ''),
location.startsWith('/')
? location
: (options.path + `/${location}`).replace(/\/{2,}/g, '/')
)
}
// args
var copy = Object.assign({}, args, {url: location, redirect})
copy.headers = JSON.parse(JSON.stringify(copy.headers || {}))
// remove authorization
if (!redirect.auth && redirect.hostname !== url.parse(location).hostname) {
var header = Object.keys(copy.headers)
.find((name) => name.toLowerCase() === 'authorization')
if (header) {
delete copy.headers[header]
}
delete copy.auth
delete copy.oauth
}
// switch to safe method
if (!redirect.method && /patch|put|post|delete/i.test(options.method)) {
copy.method = 'GET'
}
// set referer
if (redirect.referer) {
copy.headers.referer = url.resolve(
options.protocol + '//' + options.hostname +
(options.port && options.port !== 80 ? `:${options.port}` : ''),
options.path
)
}
// redirect
if (redirect.followed < redirect.max) {
redirect.followed++
return client(copy)
}
else {
var err = error({res, body, raw})
err.message = 'request-compose: exceeded maximum redirects'
throw err
}
}