如何使用fastify-cors实现一个api跨域?
我想让 [POST] localhost/product 只是这个 API 跨域。
我不知道该怎么做
fastify.register(require('fastify-cors'), {
origin:'*',
methods:['POST'],
})
这是我的 API:
{
method: 'POST',
url: '/product',
handler: productsController.addProduct,
},
回答
在这种情况下,不需要外部依赖。相反,在productsController.addProduct.
手动 CORS 标头操作示例:
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();
});
- The first one didn't work the second one does