Is it possible to have different route files in Express (NodeJS) app? - node.js

I'm a NodeJS beginner and I'm using express. My directory is like this :
__app
|_assets
|_controllers
|_somemodel.controller.js
|_models
|_somemodel.model.js
|_user.model.js
|_routes
|_route.js
|_passport.routes.js
|_somemodel.routes.js
|_views
|_note
|_index.ejs
|_passport
|_index.ejs
|_login.ejs
|_profile.ejs
...
__config
|_database.config.js
|_passport.config.js
__node_modules
package.json
server.js
the thing I wanna know is that is it possible to have a general routes file and then include or require other route files in that ? Like my route.js ?
And is this directory correct while using Express and Passport as authentication?

yes, you can require other route files into a common file like bellow.
somemodel.contoller.js
module.exports.someMethod = (req, res) => {
// do something
}
somemodel.routes.js
const controller = require("path-to-somemodel-controller")
module.exports = (app) {
app.route("/somepath")
.get(controller.someMethod)
// other methods
}
route.js
// you need to parse the app into route module
module.exports = (app) => {
require('somemodel.routes')(app);
// others goes here
}
server.js
const app = express();
require('path-to-route.js')(app
)

Related

How to structure Express server to use granular API endpoints

I currently have an Express server I'm using for a mobile app which is structured as follows (server.js):
const PostRouter = require('./api/production/Post');
const UserRouter = require('./api/production/User');
...
app.use('/posts', PostRouter)
app.use('/users', UserRouter)
and then in api/production/Post I have:
router.get('/fetch', (req, res) => {
...
}
router.get('/delete', (req, res) => {
...
}
etc..
However, I would really like to rebuild the server to match the structure of my corresponding NextJS app and its API structure, which would be something like:
/api/posts/
add-post/
index.js
fetch-all/
index.js
edit-post/
index.js
Where each index.js file contains just one endpoint/query instead of the current structure where each file has multiple queries with the router.get thing.
It looks like this is possible by creating a Router for each endpoint with something like:
const PostFetchAllRouter = require('./api/posts/fetch-all');
const PostEditPostRouter = require('./api/posts/edit-post');
...
app.use('posts/fetch-all', PostFetchAllRouter)
app.use('posts/edit-post', PostEditPostRouter)
What would be the best way to do this, please? Is there an easier way to do this without all the boilerplate in the server.js file? I'm very new to Express - please excuse if it's a naive question
You could move the "boilerplate" code to the different router files and build a router chain. But you have to write a little bit more.
server.js
|-api/
|--posts/
|---PostsRouter.js
|---fetchAll.js
|--users/
|---UserRouter.js
fetchAll.js
const express = require("express");
const FetchAll = express.Router();
FetchAll.get("/fetch", (req, res) => { res.send("/posts/fetch") });
module.exports = FetchAll;
PostsRouter.js
const express = require("express");
const FetchAll = require("./fetchAll");
const PostsRouter = express.Router();
PostsRouter.use(FetchAll);
module.exports = PostsRouter;
server.js
const express = require('express');
const PostsRouter = require("./api/posts/PostsRouter");
let app = express();
app.use("/posts", PostsRouter);
app.listen(80, () => {});
If you build it like that you would plug the small routers into the next bigger one and then use them in the server.js.
GET localhost/posts/fetch HTTP/1.1
// returns in my example the string "/posts/fetch"
Is that what you were looking for?

NodeJS Express routes in external file 404 Not Found

I'm new to NodeJs and express. My goal is to have a separate route file that contains all my application routes. So I created a file called routes.js. The content looks like this:
const express = require('express');
const router = express.Router();
router.get('auth/register', require('./controllers/auth/register'));
module.exports = router;
In my main file, I require the file with this line. The app variable contains my express instance.
app.use('/', require('./routes'));
If I call http://localhost/auth/register in my browser, I'm always running into a 404 Not Found error. When I define the route directly in the main file with app.get('/auth/register', require('./controllers/auth/register')); it works well. There are no errors in my console.
Has anyone an idea why my sperate route file does not work? Thank you for your help!
Traditionally, I do the following which is to pass the express instance into your routes module:
once I have instantiated my express instance called app
app.js
require('./routes.js')(app);
routes.js where registerUser us the function to call when the route is matched
module.exports = (app) => {
app.route('/auth/register')
.post(registerUser);
}
You want to pass app into your routes file. A good pattern for this is to import your routes in your main file, like const routes = require('./routes');
In routes, you can define all of your routes like so:
module.exports = (app, router) => {
router.route("/").get()
router.route("/something_else").post()
app.use("/api", router)
...
};
This way, in your main file, you can do: routes(app, router) and have access to app and router inside your routes.js.

Better layout express, pass app and io object to routes

I was working in express and trying to implement a better structure for the project, how would it be possible to reconstruct the layout and put all of the routes in a seperate folder. At the moment my folder structure looks like
import express from 'express';
const app = express()
app.get('/', (req, res) => {
res.send('Hello World')
})
app.listen(5656, () => {
console.log('http://localhost:5656')
})
Just a dummy example but lets say i wanted to seperate the routes and everything in a seperate folder, how would i approach it? Additionally i have socket object which i would also want to pass. If somebody can point me in a right direction of a better layout, your help would be greatly appreciated.
You would have to create something like this
const express = require('express')
const app = express()
require('./routes')(app)
app.listen(config.port,()=>{
console.log('we are now running')
})
Note that when you require routes you send an object of (app) itself, so in a route file you need to recieve this app by following this logic.
const GetController = require('./controllers/GetController')
module.exports = (app) => {
//can do other methods in the same way
app.get('/get',
GetController.getController
)
}
and inside of your GetController you can define functions such as
module.exports = {
getController(req, res) {
res.send({
message: 'Get Controller'
})
}
}
Hope that helps, if needs to pass socket.io object then just add it to your require('/routes')(app,io) and in a route file module.exports = (app, io) =>{}
Hope it helps

Arangodb/Foxx how to split routes in different files?

How could I split the routing into different files?
This what I tried, but did not work:
// file 'index.js' as main in manifest.json
const createRouter = require('#arangodb/foxx/router');
const router = createRouter();
const entries = require('./routes/entries')
entries.init(router);
module.context.use("", router);
and the entries file is working as a function:
// file './routes/entries.js'
const db = require('#arangodb').db;
// [...] more const
module.exports = {
init: function(router) {
router.post('/entries', function(req, res) {
// [...] post handle
}
}
}
1) How could I modify the router in a js file and reuse in?
module.context.use(router)
2) Any idea how to handle all js files in the folder 'routes' to define the router and so minimize the definition for route files?
you can use the funtion router.use([path], middleware, [name]): Endpoint for that.
module.context.use('/entries', require('./routes/entries'), 'entries');
For more information take a look into the docs here or in the newest Foxx tutorial here which also use child routers.

Express Routes in Parse Cloud Code Module

I am using parse.com cloud code with express to setup my routes. I have done this in the past with node, and I have my routes in separate files. So, in node I do
app.js
express = require("express");
app = exports.app = express();
require("./routes/js/account");
account.js
app = module.parent.exports.app;
app.get("/api/account/twitter", passport.authenticate("twitter"));
All the examples on parses site https://parse.com/docs/cloud_code_guide#webapp show this being done as follows.
app.js
var express = require('express');
var app = express();
app.get('/hello', function(req, res) {
res.render('hello', { message: 'Congrats, you just set up your app!' });
});
So, I would like to change the bottom to include a routes folder with separate routes files, but am not sure how to do this in parse.
I know this post is a little old, but I just wanted to post a solution for anyone still looking to get this to work.
What you need to do, is create your route file, I keep them in 'routes' forlder, for example <my_app_dir>/cloud/routes/user.js
Inside user.js you will have something that looks like this:
module.exports = function(app) {
app.get("/users/login", function(req, res) {
.. do your custom logic here ..
});
app.get("/users/logout", function(req, res) {
.. do your custom logic here ..
});
}
Then, in app.js you just include your file, but remember that you need to append cloud to the path, and pass the reference to your app instance:
require('cloud/routes/user')(app);
Also, remember that express evaluates routes in order, so you should take that into consideration when importing several route files.
I'm using a different method, have the routes in app.js, but you can probably include them in file if you prefer. Take a look at the example app,
anyblog on github
The way it works:
Set up a controller:
// Controller code in separate files.
var postsController = require('cloud/controllers/posts.js');
Add the controller route
// Show all posts on homepage
app.get('/', postsController.index);
// RESTful routes for the blog post object.
app.get('/posts', postsController.index);
app.get('/posts/new', postsController.new);
And then in posts.js, you can use exports, ex.
var Post = Parse.Object.extend('Post');
// Display all posts.
exports.index = function(req, res) {
var query = new Parse.Query(Post);
query.descending('createdAt');
query.find().then(function(results) {
res.render('posts/index', {
posts: results
});
},
function() {
res.send(500, 'Failed loading posts');
});
};
// Display a form for creating a new post.
exports.new = function(req, res) {
res.render('posts/new', {});
};
Pass the app reference to the post controller, and add the routes from there

Resources