Javascript 如何在fastify中分配基本路线内的路线
我在nodejs项目中使用fastfy作为web框架。我想从主JS文件中定义了基本路由的目录中调用我的所有路由,就像我们在express中所做的那样。我读过很多博客,但我没有找到任何与我的问题相关的答案 就像在express中一样,我们将路线指定为-Javascript 如何在fastify中分配基本路线内的路线,javascript,node.js,express,routes,fastify,Javascript,Node.js,Express,Routes,Fastify,我在nodejs项目中使用fastfy作为web框架。我想从主JS文件中定义了基本路由的目录中调用我的所有路由,就像我们在express中所做的那样。我读过很多博客,但我没有找到任何与我的问题相关的答案 就像在express中一样,我们将路线指定为- app.use('/user', user_route) 然后在用户路由中,我们定义所有其他路由方法 在Fastfy中,我使用了 fastify.register(require('./routes/users'), { prefix: '/us
app.use('/user', user_route)
然后在用户路由中,我们定义所有其他路由方法
在Fastfy中,我使用了
fastify.register(require('./routes/users'), { prefix: '/user' })
但只能调用一个函数,如-
module.exports = function (fastify, opts, done) {
fastify.get('/user', handler_v1)
done()
}
如果我想调用多路径功能怎么办?您可以使用fastify自动加载插件
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实例添加许多路由,如下所示:
'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-xgethttp://localhost:3000/user/
或curl-X PUThttp://localhost:3000/user/
对于在所有路由中全局工作的基本路由,您可以在server.js或app.js中注册它,无论您使用什么来注册服务器
fastify.register(require('../app/routes'), { prefix: 'api/v1' });
此处“../app/routes”指向您的路由目录。您定义的所有路由都将以“api/v1”作为前缀
希望这有帮助。Fastify支持这种更有组织的方式。我一步一步地解释这一点
要获得清晰的详细代码,可以按照此操作。为什么您认为只能调用一个函数?您是否尝试过添加多个
fastfy.get(…)
或fastfy.post(…)
?谢谢,它解决了我的问题。但这是宣布路线的正确方法吗?可能还有其他方法,但我不认为这种方法有任何错误。这对我帮助很大。非常感谢。
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