对于每条路线,我都必须输入相同的标头,如下所示。有没有办法全局设置这些标头,以便默认情况下将它们用于每个路由,并且可以在每个路由的基础上进行覆盖?
fastify.post("/api/users", async (request, reply) => {
try {
reply
.code(200)
header("Access-Control-Allow-Origin", "http://localhost:3000")
.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
.header("Content-Type", "application/json; charset=utf-8")
.send();
} catch (error) {
reply
.code(400)
.header("Access-Control-Allow-Origin", "http://localhost:3000")
.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
.header("Content-Type", "application/json; charset=utf-8")
.send();
}
});
您可以在使用前设置一些标题
send()
fastify.addHook('onSend', (req, repy, done) => {
reply.header("key", "value")
done()
})
fastify.post("api/users", async (req, reply) => {
try {
reply.code(200).send()
} catch (err) {
reply.code(400).send()
}
})
但是我看到你想使用 CORS,为什么不使用 fastify-cors ?