Modify or save data in request object in fastify

2019-08-18 17:19发布

I use nestjs to build a REST API.

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.

If i use express as engine it works, but with fastify it doesn't work. The data is undefined in the controller function.

The code looks like:

function mymiddleware(req, res, next) => {
    req.data = {...};
    next();
};

1条回答
放荡不羁爱自由
2楼-- · 2019-08-18 17:43

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)

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.

So, you can access the low-level Http request with .raw field.

查看更多
登录 后发表回答