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

问题描述 投票:0回答:5

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

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

app.use('/user', user_route)

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

在fastify中我用过

fastify.register(require('./routes/users'), { prefix: '/user' })

但是只能调用一个函数,比如 -

module.exports = function (fastify, opts, done) {
  fastify.get('/user', handler_v1)
  done()
}

如果我想调用多个路由功能怎么办?

javascript node.js express routes fastify
5个回答
13
投票

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

 fastify.register(require('../app/routes'), { prefix: 'api/v1' });

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

希望这有帮助。


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());
})

.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)
  })

4
投票

Fastify 支持这种更有组织的方式。我一步步解释这个。

  1. 创建一个目录名称,例如routers
  2. 该目录可能包含一个或多个 .js 文件。每个文件包含一个或多个路由。喜欢-
async function routes(fastify, options){
    fastify.get('/', async function(request, reply) {
         return {hello: 'world'} 
    }), 

    fastify.get('/bye', async function(request, reply) {
         return {bye: 'good bye'} 
    }) 
}

module.exports = routes

  1. 接下来使用 fastify-autoload 注册此目录。喜欢
const path = require('path')
const autoload = require('fastify-autoload')

async function app(fastify, options){
    //old standard routing
    //fastify.register(require('./routes/baisc-router'))

    //auto-load, based on directory 
    fastify.register(autoload,{
         dir: path.join(__dirname, 'routes')
    })
}
module.exports = app

为了获得清晰的详细代码,您可以关注这个Git存储库


0
投票

这是使用 ES6 模块的版本

// server.js
const Fastify = require('fastify')
const server = Fastify({ logger: true })
import routes from "./routes.js";
server.register(routes);
// routes.js
const routes = async (server, options) => {
  server.get("/", function (request, reply) {
    reply.send(123);
  });
};
export default routes;
© www.soinside.com 2019 - 2024. All rights reserved.