Git Product home page Git Product logo

Comments (3)

zekth avatar zekth commented on June 7, 2024

Indeed documentation is off.
The code snippet should be something like this:

fastify.register(require('fastify-cors'), (instance) => (req, callback) => {
  let corsOptions;
  // do not include CORS headers for requests from localhost
  if (/localhost/.test(req.getHeader(origin))) {
    corsOptions = { origin: false }
  } else {
    corsOptions = { origin: true }
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

Which is still confusing. See this test for more explicit use case:

test('Should support dynamic config (Promise)', t => {
t.plan(16)
const configs = [{
origin: 'example.com',
methods: 'GET',
credentials: true,
exposedHeaders: ['foo', 'bar'],
allowedHeaders: ['baz', 'woo'],
maxAge: 123
}, {
origin: 'sample.com',
methods: 'GET',
credentials: true,
exposedHeaders: ['zoo', 'bar'],
allowedHeaders: ['baz', 'foo'],
maxAge: 321
}]
const fastify = Fastify()
let requestId = 0
const configDelegation = function (req) {
// request should have id
t.ok(req.id)
// request should not have send
t.notOk(req.send)
const config = configs[requestId]
requestId++
if (config) {
return Promise.resolve(config)
} else {
return Promise.reject(new Error('ouch'))
}
}
fastify.register(cors, () => configDelegation)
fastify.get('/', (req, reply) => {
reply.send('ok')
})
fastify.inject({
method: 'GET',
url: '/'
}, (err, res) => {
t.error(err)
delete res.headers.date
t.equal(res.statusCode, 200)
t.equal(res.payload, 'ok')
t.match(res.headers, {
'access-control-allow-origin': 'example.com',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'access-control-expose-headers': 'foo, bar',
'content-length': '2'
})
})
fastify.inject({
method: 'OPTIONS',
url: '/',
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': 'sample.com',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'access-control-expose-headers': 'zoo, bar',
'access-control-allow-methods': 'GET',
'access-control-allow-headers': 'baz, foo',
'access-control-max-age': '321',
'content-length': '0'
})
})
fastify.inject({
method: 'GET',
url: '/',
headers: {
'access-control-request-method': 'GET',
origin: 'example.com'
}
}, (err, res) => {
t.error(err)
t.equal(res.statusCode, 500)
})
})

from fastify-cors.

tngflx avatar tngflx commented on June 7, 2024

Ok found a solution :

fastify.register(require('fastify-cors'), (instance) => async (req, callback) => {
    let corsOptions = {
        credentials: true,
        allowedHeaders: ["Origin, X-Requested-With, Content-Type, Accept"],
        origin: false
    }
    // do not include CORS headers for requests from localhost
    let originHostname = req.headers.origin || req.ip || '';
    if (/(localhost|ngrok|127.0.0.1)/g.test(originHostname)) {
        corsOptions.origin = true
    } else {
        corsOptions.origin = false
    }
    callback(null, corsOptions) // callback expects two parameters: error and options
})

This can dynamically match all kind of origin and assign cors for each route. its working so far.

from fastify-cors.

Sikora00 avatar Sikora00 commented on June 7, 2024

I was sorry when I saw it 😟

from fastify-cors.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.