Modify or save data in request object in fastify

2019-08-18 17:50发布

问题:

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:

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.