Answer the question
In order to leave comments, you need to log in
How does routing work in Express?
Help with routing in Node.js Express framework.
I am writing an application - a note manager, and at this time there are routings for all CRUD-operations of notes.
app.get('/notes', (req, res)=> {
db.listNotes().then(data => res.send(data));
});
app.post('/notes', (req, res)=> {
db.createNote(req.body).then(data => res.send(data));
});
app.delete('/notes/:id', (req, res)=> {
db.deleteNote(req.params.id).then(data => res.send(data));
});
app.put('notes/:id', (req, res)=> {
db.updateNote(req.params.id).then(data => res.send(data));
});
Answer the question
In order to leave comments, you need to log in
same functions?
After all, you can put it in a separate function, and do something like:
function crud(app, path, controller) {
app.get(path, controller.get);
app.post(path, controller.post);
app.delete(`${path}/:id`, controller.delete);
app.put(`${path}/:id`, controller.put);
}
class NotesController {
get(req, res) {
db.listNotes().then(data => res.send(data));
}
post(req, res) {
db.createNote(req.body).then(data => res.send(data));
}
delete(req, res) {
db.deleteNote(req.params.id).then(data => res.send(data));
}
put(req, res) {
db.updateNote(req.params.id).then(data => res.send(data));
}
}
crud(app, '/notes', new NotesController);
crud(app, '/users', new UsersController);
Uncompromising adherence to the DRY principle:
[
['get', '/notes', 'listNotes'],
['post', '/notes', 'createNote'],
['delete', '/notes/:id', 'deleteNote'],
['put', '/notes/:id', 'updateNote'],
].map(([app_method, route, db_method]) => {
app[app_method](route, (req, res) => {
db[db_method](req.params.id).then(data => res.send(data));
});
});
Regular expressions can be used as a route. There is a .any() handler in which you can extract a specific type of request from req (get/post/delete/put). Well, there is app.route() , which can chain handlers into one chain (in combination with regular expressions). app.route().get().post().put().delete()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question