gpt4 book ai didi

fastify 为所有路由设置回复头

转载 作者:行者123 更新时间:2023-12-02 02:06:48 25 4
gpt4 key购买 nike

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

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()之前设置一些header


fastify.addHook('preHandler', (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

关于fastify 为所有路由设置回复头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68338349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com