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

Viewed 12047

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,
},
1 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();
});
Related