9

I want to let [POST] localhost/product just this API to cross-domain.

I don't know how to do it

fastify.register(require('fastify-cors'), {
  origin:'*',
  methods:['POST'],
  
})

this is my API:

{
      method: 'POST',
      url: '/product',
      handler: productsController.addProduct,
},
Shams Nahid
  • 6,239
  • 8
  • 28
  • 39
radiorz
  • 1,459
  • 4
  • 18
  • 36

2 Answers2

12

In this case, an external dependency is not required. Instead, set the CORS headers manually in productsController.addProduct.

Example of manual CORS header manipulation:

function addProduct(request, reply) {
  reply.header("Access-Control-Allow-Origin", "*");
  reply.header("Access-Control-Allow-Methods", "POST");
  // ... more code here ...
}

If you still want to use fastify-cors, try something like this:

fastify.register((fastify, options, done) => {
  fastify.register(require("fastify-cors"), {
    origin: "*",
    methods: ["POST"]
  });
  fastify.route({
    method: "POST",
    url: "/product",
    handler: productsController.addProduct
  });
  done();
});
luawtf
  • 576
  • 8
  • 21
2

This is currently the top hit for "fastify cors" on multiple search engines. If -- like me -- you saw that an entire npm package exists for it but would rather just set a few headers on your own, here is how:

const server = Fastify({});
server.addHook('preHandler', (req, res, done) => {

  // example logic for conditionally adding headers
  const allowedPaths = ["/some", "/list", "/of", "/paths"];
  if (allowedPaths.includes(req.routerPath)) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST");
    res.header("Access-Control-Allow-Headers",  "*");
  }

  const isPreflight = /options/i.test(req.method);
  if (isPreflight) {
    return res.send();
  }
      
  done();
})
Seph Reed
  • 8,797
  • 11
  • 60
  • 125