Skip to content

Commit 02ef978

Browse files
authored
Rewrite location header (#25)
1 parent 2b8c231 commit 02ef978

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

index.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,28 @@ module.exports = async function (fastify, opts) {
1414
fromOpts.base = opts.upstream
1515
fromOpts.prefix = undefined
1616

17+
const oldRewriteHeaders = (opts.replyOptions || {}).rewriteHeaders
18+
const replyOpts = Object.assign({}, opts.replyOpts, {
19+
rewriteHeaders
20+
})
21+
fromOpts.rewriteHeaders = rewriteHeaders
22+
1723
fastify.register(From, fromOpts)
1824

1925
fastify.addContentTypeParser('application/json', bodyParser)
2026
fastify.addContentTypeParser('*', bodyParser)
2127

28+
function rewriteHeaders (headers) {
29+
const location = headers.location
30+
if (location) {
31+
headers.location = location.replace(rewritePrefix, fastify.basePath)
32+
}
33+
if (oldRewriteHeaders) {
34+
headers = oldRewriteHeaders(headers)
35+
}
36+
return headers
37+
}
38+
2239
function bodyParser (req, done) {
2340
done(null, req)
2441
}
@@ -29,6 +46,6 @@ module.exports = async function (fastify, opts) {
2946
function reply (request, reply) {
3047
var dest = request.req.url
3148
dest = dest.replace(this.basePath, rewritePrefix)
32-
reply.from(dest || '/', opts.replyOptions)
49+
reply.from(dest || '/', replyOpts)
3350
}
3451
}

test.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ async function run () {
1818

1919
origin.post('/this-has-data', async (request, reply) => {
2020
if (request.body.hello === 'world') {
21+
reply.header('location', '/something')
2122
return { something: 'posted' }
2223
}
2324
throw new Error('kaboom')
@@ -184,7 +185,7 @@ async function run () {
184185
t.match(headers, { 'x-test': 'test' })
185186
})
186187

187-
test('keepPrefix true', async (t) => {
188+
test('rewritePrefix', async (t) => {
188189
const proxyServer = Fastify()
189190

190191
proxyServer.register(proxy, {
@@ -202,6 +203,27 @@ async function run () {
202203
const firstProxyPrefix = await got(`http://localhost:${proxyServer.server.address().port}/api/a`)
203204
t.equal(firstProxyPrefix.body, 'this is /api2/a')
204205
})
206+
207+
test('rewrite location headers', async (t) => {
208+
const proxyServer = Fastify()
209+
210+
proxyServer.register(proxy, {
211+
upstream: `http://localhost:${origin.server.address().port}`,
212+
prefix: '/api'
213+
})
214+
215+
await proxyServer.listen(0)
216+
217+
t.tearDown(() => {
218+
proxyServer.close()
219+
})
220+
221+
const { headers: { location } } = await got(`http://localhost:${proxyServer.server.address().port}/api/this-has-data`, {
222+
body: { hello: 'world' },
223+
json: true
224+
})
225+
t.equal(location, '/api/something')
226+
})
205227
}
206228

207229
run()

0 commit comments

Comments
 (0)