Daily : Tuesday 25th of June: Plan changed

Alessandro - Jun 27 - - Dev Community

Hello ☕,

I was supposed to start my exercise of creating a real-time chatbot using Express and Stream.IO, but when I sat down at my machine this morning, I felt it might be necessary to continue understanding the basic mechanics of the two libraries in question.

So, I opened the Express website: https://expressjs.com/ and ended up learning some interesting things.

  1. The Availability of an Express Project Generator...

    Okay, okay, it's the first page of the project ^^. But it's important to run the command and dig into the generated code. More importantly, get it running. Navigate to the bin directory (via the terminal or by right-clicking on the directory in VS Code and selecting Open in Integrated Terminal) and execute the following command in the terminal:

    node www
    

    Then go to http://localhost:3000. You'll realize the importance of separating scripts to gain visibility later and the role of app.use().

  2. app.use and Static Files

    It makes more sense, after seeing the auto-generated project, that additional tools are available to use and serve static pages like index.html and its related CSS stored in the public directory. You can use the following code to display the index.html page when the user goes to http://localhost:3000:

    app.use(express.static('public'));
    
  3. Routes in a Separate File under Routes

    Using import and export in Express is not different from other setups, but it's important to see it at least once to understand how it works. Plus, it gives me extra practice since I always have to convert the code to ES6 format to make it work 😄.

  4. Middleware

    Although I had seen middleware in my LinkedIn training, the topic was skimmed over, and I realized I didn't really understand how to use it. The example from the Express site helped me truly grasp its power.

    The following example (from the documentation) shows a requestTime function called with app.use(), making req.requestTime available in all routes (the example shows the use of the variable in res.send()). However, it's important to declare functions before the routes; otherwise, the middleware will never be called.

    import express from 'express';
    const app = express();
    
    const requestTime = function (req, res, next) {
        req.requestTime = Date.now();
        next();
    };
    
    app.use(requestTime);
    
    app.get('/', (req, res) => {
        let responseText = 'Hello World!<br>';
        responseText += `<small>Requested at: ${req.requestTime}</small><br>`;
        res.send(responseText);
    });
    
    app.listen(3000);
    

I don't regret deviating from my main goal because I still made progress by going through the Express documentation and, most importantly, by sharing this with you today.

And you, what did you learn today? 🌟

. . . . . . . .