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,
},
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();
});
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();
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With