Prefix in Node restify

Asked

Viewed 88 times

0

I have my module in the nodejs and I would like to have a prefix so I don’t have to repeat every time the beginning:

For example, in the file route js

const db = require('../services')
const routes = (server) => {
    server.get('/v1', (req, res, next) => {
        res.send('Engoy the silence')
        next()
    })

    server.get('/v1/beers', async (req, res, next) => {
        try{
            res.send( await db.beers().all() )
        }catch(error){
            res.send(error)
        }
        next()
    })
}
module.exports = routes

I would like to set a prefix earlier in mine index js.. I tried so:

server.use('/api', function(req, res, next){

})

routes(server)

But I don’t know what else to do

How do I create a prefix?

1 answer

1


Carlos, a suggestion would be to export the Routes and configure them in the server.js (your project’s configuration file). I did it using Express, follow the idea:

// allows receive all request types
userRoute = require('./src/routes/userRoute');
teamRoute = require('./src/routes/teamRoute');
projectRoute = require('./src/routes/projectRoute');

routes = [
    userRoute,
    teamRoute,
    projectRoute,
];


app.use('/api/v1', ...routes);

This way, all Routes endpoins will start with '/api/v1' + the endpoint address of the route you set up.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.