修改或保存数据到请求对象中 [英] Modify or save data in request object in fastify
问题描述
我使用nestjs构建REST API.
I use nestjs to build a REST API.
我有一个中间件,该中间件从redis缓存中加载数据,并应将其保存在请求对象中以在控制器功能中进行访问.
I have a middleware which loads data from redis cache and should save it in the request object to access it in the controller function.
如果我使用express作为引擎,它可以工作,但是使用fastify则不能工作.数据在控制器功能中未定义.
If i use express as engine it works, but with fastify it doesn't work. The data is undefined in the controller function.
代码如下:
function mymiddleware(req, res, next) => {
req.data = {...};
next();
};
推荐答案
这是一个简单的工作示例:
this is a simple working example:
const fastify = require('fastify')({ logger: true })
fastify.use(function (req, res, next) {
console.log('middy')
req.data = { hello: 'world' }
next();
})
fastify.get('/', (req, res) => {
res.send(`hello ${req.raw.data.hello}`)
})
fastify.listen(3000)
我认为您的问题是由于req
对象造成的:在中间件(使用.use
注册)中,您将获得标准的Node.js请求,而不是在fastify处理程序中增强的HTTPRequest.
I think that your problem is due to the req
object: in middleware (registered using .use
you will get the standard Node.js request, instead of augmented HTTPRequest in the fastify handler.
因此,您可以通过.raw
字段访问低级Http请求.
So, you can access the low-level Http request with .raw
field.
这篇关于修改或保存数据到请求对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!