fastify 为所有路由设置回复标头

问题描述 投票:0回答:1

对于每条路线,我都必须输入相同的标头,如下所示。有没有办法全局设置这些标头,以便默认情况下将它们用于每个路由,并且可以在每个路由的基础上进行覆盖?

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();
    }
});
fastify
1个回答
8
投票

您可以在使用前设置一些标题

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

© www.soinside.com 2019 - 2024. All rights reserved.