Skip to content

Commit 5e6aeb9

Browse files
authored
fix: respect custom status code when successfully send file (#476)
1 parent c0ca1c9 commit 5e6aeb9

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

index.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,11 @@ async function fastifyStatic (fastify, opts) {
350350
break
351351
}
352352
case 'file': {
353-
reply.code(statusCode)
353+
// reply.raw.statusCode by default 200
354+
// when ever the user changed it, we respect the status code
355+
// otherwise use send provided status code
356+
const newStatusCode = reply.statusCode !== 200 ? reply.statusCode : statusCode
357+
reply.code(newStatusCode)
354358
if (setHeaders !== undefined) {
355359
setHeaders(reply.raw, metadata.path, metadata.stat)
356360
}

test/static.test.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4023,3 +4023,41 @@ t.test('content-length in head route should not return zero when using wildcard'
40234023
})
40244024
})
40254025
})
4026+
4027+
t.test('respect the .code when using with sendFile', t => {
4028+
t.plan(6)
4029+
4030+
const pluginOptions = {
4031+
root: path.join(__dirname, '/static')
4032+
}
4033+
const fastify = Fastify()
4034+
4035+
fastify.register(fastifyStatic, pluginOptions)
4036+
4037+
fastify.get('/custom', (_, reply) => {
4038+
return reply.code(404).type('text/html').sendFile('foo.html')
4039+
})
4040+
4041+
t.teardown(fastify.close.bind(fastify))
4042+
4043+
fastify.listen({ port: 0 }, err => {
4044+
t.error(err)
4045+
4046+
fastify.server.unref()
4047+
4048+
const file = fs.readFileSync(path.join(__dirname, '/static/foo.html'))
4049+
const contentLength = Buffer.byteLength(file).toString()
4050+
4051+
simple.concat({
4052+
method: 'HEAD',
4053+
url: 'http://localhost:' + fastify.server.address().port + '/custom',
4054+
followRedirect: false
4055+
}, (err, response, body) => {
4056+
t.error(err)
4057+
t.equal(response.statusCode, 404)
4058+
t.equal(response.headers['content-type'], 'text/html; charset=UTF-8')
4059+
t.equal(response.headers['content-length'], contentLength)
4060+
t.equal(body.toString(), '')
4061+
})
4062+
})
4063+
})

0 commit comments

Comments
 (0)