Cookie1980
Cookie1980

Reputation: 108

NodeJS, express - routing

I´ve setup a little NodeJS API with 'expressjs'. In my code I have some similar code blocks looking like this:

app.get('/api/my/path', (req, res) => {
  doSomethingUseful();
});

All thoses requests do something different, so the function being called is always different too.

I´m asking myself if this is good practice for writing code in NodeJS or not. If there is a better / cleaner way of writing all those paths I would appreciate if you could tell me how or at least giving me a place to look for it.

EDIT 1: To be clear: I ask if it´s a good idea to write a lot of 'app.get(...)' into one source code file or if there is a better way?

Upvotes: 3

Views: 1737

Answers (2)

Calvintwr
Calvintwr

Reputation: 8798

Use a simple module, don't be invoking routes until you form a heap.

Try Route Magic

You want to do just 2 lines of code and have the module read your directory and file structure to handle all the app.use routing invocations, like this:

const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')

For those you want to handle manually, just don't use pass the directory to Magic.

Upvotes: 1

SanSolo
SanSolo

Reputation: 2373

Yes there is a better way than writing all routes in one file. For example, let us say you have routes for users and questions. For users, you want get/set/put/delete for profile, and similarly for questions.So you create the following folder structure: /api/users and /api/questions In /api/users,

const express=require('express')
 const router=express.Router()

 //this handles route: /users
 router.get('/',(req,res)=>{})

 //this handles route: /users/profile
 router.get('/profile',(req,res){})

 //this is to retrieve profile of specific user by user id :/users/profile/:userID
 router.get('/profile/:userId',(req,res))


 router.post('/profile',(req,res))
 .
 .

Then, in your index.js or entry point of your project,

const users=require('./api/users')
const questions=require('./api/questions')
app=require('express')

app.use('/users',users)
app.use('/questions',questions)

So in effect, you say for any /users route, refer to the users.js file, for any /questions routes, refer questions.js file and so on

Upvotes: 5

Related Questions