如何在fastify中的基本路由内分配路由

ADI*_*IKA 16 javascript routes node.js express fastify

我在我的 Nodejs 项目中使用 fastify 作为 Web 框架。我想从一个目录中调用所有路由,该目录在主 JS 文件中定义了基本路由,就像我们在express中所做的那样。我读过很多博客,但没有找到与我的问题相关的答案

就像在快递中一样,我们将路线分配为-

app.use('/user', user_route)
Run Code Online (Sandbox Code Playgroud)

然后在 user_route 中我们定义所有其他路由方法。

在 fastify 中我用过

fastify.register(require('./routes/users'), { prefix: '/user' })
Run Code Online (Sandbox Code Playgroud)

但这样就只能调用一个函数——

module.exports = function (fastify, opts, done) {
  fastify.get('/user', handler_v1)
  done()
}
Run Code Online (Sandbox Code Playgroud)

如果我想调用多个路由函数怎么办?

Ant*_*tta 13

为了使基本路由在所有路由中全局工作,您可以在 server.js 或 app.js 中注册它,无论您使用什么来注册服务器。

 fastify.register(require('../app/routes'), { prefix: 'api/v1' });
Run Code Online (Sandbox Code Playgroud)

这里的“../app/routes”指向您的路线目录。您定义的所有路由都将以“api/v1”为前缀

希望这可以帮助。


Man*_*lon 8

您可以向 fastify 实例添加许多路由,如下所示:

'use strict'

const Fastify = require('fastify')
const fastify = Fastify({ logger: true })

fastify.register((instance, opts, next) => {

  instance.get('/', (req, res) => { res.send(req.raw.method) })
  instance.post('/', (req, res) => { res.send(req.raw.method) })
  instance.put('/', (req, res) => { res.send(req.raw.method) })
  instance.patch('/', (req, res) => { res.send(req.raw.method) })

  instance.get('/other', (req, res) => { res.send('other code') })

  next()
}, { prefix: 'user' })


fastify.listen(3000, () => {
  console.log(fastify.printRoutes());
})
Run Code Online (Sandbox Code Playgroud)

.register方法仅需要封装上下文和插件。这对于将代码库分割成更小的文件并仅加载您需要的插件很有用。

通过这种方式,您将拥有一个针对不同 HTTP 方法做出不同回复的单一路由:curl -X GET http://localhost:3000/user/或者curl -X PUT http://localhost:3000/user/


小智 7

您可以使用 fastify-autoload 插件

const AutoLoad = require('fastify-autoload')
// define your routes in one of these
fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'services'),
    options: Object.assign({ prefix: '/api' }, opts)
  })
Run Code Online (Sandbox Code Playgroud)