如何使用 fastify-cors 只允许一个 api 跨域?

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

我想让 [POST] localhost/product 就是这个API跨域

我不知道怎么做

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

这是我的 API:

{
      method: 'POST',
      url: '/product',
      handler: productsController.addProduct,
},

在这种情况下,不需要外部依赖。相反,在 productsController.addProduct.

中手动设置 CORS headers

手动 CORS header 操作示例:

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

如果您仍想使用 fastify-cors,请尝试这样的操作:

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