fastify-cors: 404 Not Found on OPTIONS request

Completely stumped. I have the cors plugin installed, and two routes as follows:

module.exports = async (app, opts) => {
  app.get('/bar', async (request, reply) => {
    return { hello: 'bar called' }
  })

  app.get('/foo', async (request, reply) => {
    return { hello: 'foo called' }
  })
}

OPTIONS requests seem to be working, and are handled by the onRequest hook in the fastify-cors plugin, but when I change the path of the bar route, to anything else that doesn’t start with bar… I get a 404 not found response.

e.g.:

module.exports = async (app, opts) => {
  app.get('/fuzzy', async (request, reply) => {
    return { hello: 'bar called' }
  })
}

curl -X OPTIONS http://127.0.0.1:3000/fuzzy

returns

{"statusCode":404,"error":"Not Found","message":"Not Found"}

Any ideas?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 16 (4 by maintainers)

Most upvoted comments

Apologies for the slow reply. What we think might be happening, is that in our application, we are registering a main app.js plugin, after index.js. https://github.com/58bits/fastify-20/blob/master/index.js - and that if instead the fastify-cors module is loaded in index.js (top level scope?) it works.

We still don’t know 100% why, and have not had time to dig into find-my-way, or the problem in more detail.

For now - we’ve simply created our own plugin, using the '/*' catch-all route as follows (leaning heavily on the fastify-cors module as an example).

'use strict'

const fp = require('fastify-plugin')

async function setup (app) {
  // Wildcard OPTIONS handler for CORS preflight requests
  app.route({
    method: 'OPTIONS',
    url: '/*',
    handler: async (request, reply) => {

      var reqAllowedHeaders = request.headers['access-control-request-headers']
      if (reqAllowedHeaders !== undefined) {
        reply.header('Access-Control-Allow-Headers', reqAllowedHeaders)
      }
      reply.code(204)
        .header('Content-Length', '0')
        .header('Access-Control-Allow-Origin', 'http://localhost:8080')
        .header('Access-Control-Allow-Credentials', true)
        .header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE')
        .send()
    }
  })

  // CORS reply - 'Access-Control-Allow-Origin', '*' for now..
  // See https://github.com/fastify/fastify-cors/issues/20
  app.addHook('onRequest', function (request, reply, next) {
    reply.header('Access-Control-Allow-Origin', 'http://localhost:8080')
    reply.header('Access-Control-Allow-Credentials', true)
    next()
  })
}

module.exports = fp(setup)

This is a different problem as OP says OPTIONS, but I struggled to fix curl -I http://127.0.0.1:3000 returns 404.

For others who miss the document, this helped me a lot.

const app = fastify({
    exposeHeadRoutes: true,       // <-- this option
})

Related

Sorry both @daveamayombo and I are on the road until later this week. Stay tuned…