我在我的 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()
}
如果我想调用多个路由功能怎么办?
要使基本路由在所有路由中全局工作,您可以在 server.js 或 app.js 中注册它,无论您使用什么来注册服务器。
fastify.register(require('../app/routes'), { prefix: 'api/v1' });
这里“../app/routes”指向您的路线目录。您定义的所有路由都将以“api/v1”为前缀
希望这有帮助。
您可以向 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/
您可以使用 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)
})
Fastify 支持这种更有组织的方式。我一步步解释这个。
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
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存储库。
这是使用 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;