McFiddlyWiddly McFiddlyWiddly - 1 month ago 9
Node.js Question

How do I separate one route in a different module and "require it" in index.js?

I have a Node/Express application, and I need to move one route to a different file.
This is my index.js.

'use strict';

let express = require('express'),
bodyParser = require('body-parser'),
logger = require('morgan'),
_ = require('lodash');



let app = express();
app.use(logger('combined'));
app.use(express.static('public'));
app.use(bodyParser.json({}));
app.use(bodyParser.urlencoded({ extended: true }));

console.log("I am open");

let users = [///stuff ];

let games = [];


// Handle POST to create a user session
app.post('/v1/session', function(req, res) {
// do things
});

// Handle POST to create a new user account
app.post('/v1/user', function(req, res) {
// do things
});

// Handle GET to fetch user information
app.get('/v1/user/:username', function(req, res) {
// do things
});

// Handle POST to create a new game
app.post('/v1/game', function(req, res) {
// do things
});

// Handle GET to fetch game information
app.get('/v1/game/:id', function(req, res) {
// do things
});


let server = app.listen(8080, function () {
console.log('Example app listening on ' + server.address().port);
});


I want to have a new server side route
(GET /v1/game/shuffle?jokers=false)
, but I don't quite understand how to separate it into a new file, perhaps in
./routes/shuffleRoute.js
.

I read through this one, but I don't quite understand it due to the file names being similar. How to separate routes on Node.js and Express 4?

And I'm just trying to separate one route, not all.

Answer

Create a file in routes, called shuffleRoute.js. In this file write something like

var express = require('express');
var router = express.Router();
router.get("/shuffle", function (req, res, next) {
    // magic here
});

router.get("/:id", function (req, res, next) {
    // more magic here
});

module.exports = router;

and in your server.js

app.get("/v1/games", require("./routes/shuffleRoute.js"));

It's important to node that in your case, as you are using a param for id, your shuffle route needs to come before the :id route. Otherwise express will interpret shuffle as an id (which will hopefully not be an id)

If you only want to "outsource" "/v1/games/shuffle, make sure that comes before app.get("/v1/games/:id"...) in your server.js file

Comments