Skip to content

Commit

Permalink
add support for nested index routes (fixes fastify#281)
Browse files Browse the repository at this point in the history
  • Loading branch information
GlenTiki authored Dec 8, 2023
1 parent ec470fc commit c4b8136
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
12 changes: 8 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,21 @@ function fastifyCors (fastify, opts, next) {
// preflight requests BEFORE possible authentication plugins. If the preflight reply
// occurred in this handler, other plugins may deny the request since the browser will
// remove most headers (such as the Authentication header).
//
// This route simply enables fastify to accept preflight requests.
fastify.options('/*', { schema: { hide: hideOptionsRoute } }, (req, reply) => {
const handlerOptions = { schema: { hide: hideOptionsRoute } }
const handler = (req, reply) => {
if (!req.corsPreflightEnabled) {
// Do not handle preflight requests if the origin option disabled CORS
reply.callNotFound()
return
}

reply.send()
})
}

// This route enables fastify to accept preflight requests on all nested routes, as well as the index route in prefixed setups
// https://github.com/fastify/fastify-cors/issues/281
fastify.options('/', handlerOptions, handler)
fastify.options('/*', handlerOptions, handler)

next()
}
Expand Down
33 changes: 33 additions & 0 deletions test/preflight.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,36 @@ test('Can override preflight response with preflightContinue', t => {
})
})
})

test('Can get a preflight response on prefixed index routes', t => {
t.plan(4)

const fastify = Fastify()
const noop = () => {}
const prefixRoutes = (app, done) => {
app.register(cors)
app.get("/", noop)
}
fastify.register(prefixRoutes, {prefix: "test"})

fastify.inject({
method: 'OPTIONS',
url: '/test',
headers: {
'access-control-request-method': 'GET',
origin: 'example.com'
}
}, (err, res) => {
t.error(err)
delete res.headers.date
t.equal(res.statusCode, 204)
t.equal(res.payload, '')
t.match(res.headers, {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'access-control-allow-headers': 'x-requested-with',
vary: 'Origin, Access-Control-Request-Headers',
'content-length': '0'
})
})
})

0 comments on commit c4b8136

Please sign in to comment.