Fastify 中间件 - 访问查询和参数?

Cal*_*v J 3 javascript middleware node.js fastify

试图让中间件在 Fastify 中工作 - 我似乎无权访问查询或参数。文档说:

Fastify 支持开箱即用的 Express/Restify/Connect 中间件,这意味着您只需插入旧代码即可运行!(顺便说一下,更快)

但举个简单的例子:

fastify.use(function(req, res, next) {
  console.log('req.query', req.query);   // undefined
  console.log('req.params', req.params); // undefined
  next();
});
Run Code Online (Sandbox Code Playgroud)

如果我添加/限制网址,则相同:

fastify.use('/foo', function(req, res, next) {
Run Code Online (Sandbox Code Playgroud)

我确定我遗漏了一些东西,但文档确实声称它“正常工作”-如果您无法访问 qs,我看不出怎么办?

[我想我可以重写以使用钩子,但我真的很感兴趣我打算如何使用中间件来做到这一点]

谢谢

Mat*_*Can 5

This was answered when Fastify 2 was the main version. This answer may not be correct for Fastify 3


While Fastify is compatible with Express/Restify method signature, it isn't exactly the same values being passed in. The method signature is:

/**
 * Generic middleware method
 * @param {http.IncomingMessage} req
 * @param {http.ServerResponse} res
*/
const middleware = (req, res) => {
}

fastify.use(middleware)
Run Code Online (Sandbox Code Playgroud)

When using .use, Fastify only deals with the Node.js HTTP classes which do not provide the .params or .query fields.

Express adds these fields as a nicety to developers. If the middleware you use relies on those features, unfortunately, it will not be a direct drop in.

All is not lost

If you choose to migrate your middleware to Fastify, the .params and .query fields are available on the Request object.

Using the middleware in your question, this is what the Fastify version would look like.

fastify.addHook('onRequest', function(request, reply, done) {
  console.log('query', request.query);
  console.log('params', request.params);

  done();
})
Run Code Online (Sandbox Code Playgroud)

Fastify is asking developers to think more in terms of Hooks and less in terms of Middleware. This provides more flexibility and greater speed but can be a little more complicated to write at times.

Additional reading

The Lifecycle and Hooks documentation on the Fastify site give more detail on how these pieces work together.

The Middleware documentation provides more detail on what features are supported.

Somewhat related, using Plugins you are able to scope to a particular path.

References

Express middleware support

From the Middleware documentation:

Furthermore, methods added by Express and Restify to the enhanced versions of req and res are not supported in Fastify middlewares.

and

Express 大量修改了节点核心 Request 和 Response 对象的原型,因此 Fastify 无法保证完全的中间件兼容性。

快速添加.params.query

Express 添加.query到请求 以及Express 运行查询中间件的位置

Express 添加参数到 route