如何使用 fastify-cors 实现一个 api 跨域?

rad*_*orz 2 node.js fastify

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

我不知道该怎么做

fastify.register(require('fastify-cors'), {
  origin:'*',
  methods:['POST'],
  
})
Run Code Online (Sandbox Code Playgroud)

这是我的 API:

{
      method: 'POST',
      url: '/product',
      handler: productsController.addProduct,
},
Run Code Online (Sandbox Code Playgroud)

Sep*_*eed 7

目前,这是“fastify cors”在多个搜索引擎上的热门搜索。如果像我一样,您看到它存在整个 npm 包,但宁愿自己设置一些标头,则方法如下:

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();
})
Run Code Online (Sandbox Code Playgroud)


lua*_*wtf 6

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

手动 CORS 标头操作示例:

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

如果您仍然想使用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();
});
Run Code Online (Sandbox Code Playgroud)

  • 第一个没用第二个可以 (2认同)