Last active
July 14, 2020 06:04
-
-
Save RocketFever22/126f02af5a6612b554801c34c26cbf81 to your computer and use it in GitHub Desktop.
A simple way to approach routing in express.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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