Skip to content

Instantly share code, notes, and snippets.

@RocketFever22
Last active July 14, 2020 06:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RocketFever22/126f02af5a6612b554801c34c26cbf81 to your computer and use it in GitHub Desktop.
Save RocketFever22/126f02af5a6612b554801c34c26cbf81 to your computer and use it in GitHub Desktop.
A simple way to approach routing in express.js
// This file should be in routes/models.js
const routes = require('express').Router();
const data = require('../data.json');
routes.get('/', (req, res) => {
res.status(200).json(data.models);
});
routes.get('/:modelId', (req, res) => {
const modelId = req.params.modelId * 1;
const model = data.models.find(m => m.id === modelId);
res.status(200).json({ model });
});
module.exports = routes;
'use strict';
const express = require('express');
// We don't need the .js
const models = require('./routes/models');
const PORT = 8080;
const HOST = '0.0.0.0';
const app = express();
// Here every route method is available: /models, /models/:modelId
app.use('/models', models);
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment