I wonder if it makes any difference between using only routes , or routes with controllers in node js could someone give me some examples of how to implement routes and controllers on the node using express js ?
I wonder if it makes any difference between using only routes , or routes with controllers in node js could someone give me some examples of how to implement routes and controllers on the node using express js ?
There is a difference between using only routes, and using routes with controllers, the difference is whether you need logic on the server or if you are serving static content that does not need logic.
The simplest example is using express to serve static files , with no routes, no logic. Simply mapping:
app.use('/', express.static('minha-diretoria-root-do-site'))
Imagine that you have 2 HTML files that you want to send to the client. In practice you always have a controller, but in this case it does so little that we are going to say that it is just a route to serving files.
Example with no great logic to justify a controller:
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../minha-diretoria-root-do-site', 'index.html'));
});
app.get('/contacto', (req, res) => {
res.sendFile(path.join(__dirname, '../minha-diretoria-root-do-site', 'contacto.html'));
});
Example where you need driver , which can be in the same file as the example here, or in different files if it is extensive:
app.get('/casas', (req, res) => {
const query = 'SELECT name, price, rooms FROM houses';
db.query(query, (err, rows) => {
Promise.all([...rows].map(converterCambio)).then(items => {
res.render('items', items);
});
});
});
In this last example you make 2 asynchronous steps, and here the thing can complicate and be extensive, hence the need for the controller. In the example I imagine that I send to the renderer, such as ejs
, or Pug
to compile the page with the array I sent it.