Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fastify-cors to enable just one api to cross domain?

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,
},
like image 668
radiorz Avatar asked Dec 31 '22 17:12

radiorz


2 Answers

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();
});
like image 104
luawtf Avatar answered Apr 27 '23 07:04

luawtf


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();
})
like image 33
Seph Reed Avatar answered Apr 27 '23 08:04

Seph Reed