EXPRESS

Athena's Intro to Backend Programming Using Node.js & Express

Code a backend – earn stickers, knowledge, and artifacts :3


Here's a break down on how the home_page/demo/api works. Checkout the full code here!

Let's explore together the backend of this app. In this particular case, something we're gonna break down what we call an API.


This app uses the Fetch API which defines how network requests(GET,PUT, POST, DELETE) are handled by an application.

While you go through this demo, we highly encourage you to open your console (f12) and go to the network tab:3

network tab gif

1. The frontend side is just a simple html form:

(srry it doesn't display great on mobile)

        
            // home.html

            <form id="message-form">
              <label for="nickname">Nickname:</label><br/>
              <input required type="text" id="nickname" name="nickname" placeholder="Your nickname" maxlength="50">
            
              <label for="message">Send a message to other space explorers viewing this page</label><br/>
              <textarea placeholder="Your message" maxlength="256" id="message" cols="30" required></textarea><br/>
            
              <button id="send-button" type="submit">
                <img src="/public/click.gif" alt="Send">
              </button>
            </form>
        
    




2. This form is connected with the backend through a simple script:

        
            //script.js

            [....] the rest of the code

            fetch('/messages', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message, nickname }),
            })
            .then(response => response.json())
            .then(() => {
              loadMessages();
              messageInput.value = '';
            })
            .catch(error => {
              console.error('Error submitting message:', error);
            });
        
    

This script is executed when the form is submitted. It makes a POST request to the backend /messages endpoint


3. The backend & the /message endpoint.

            
                // app.js

                const app = express(); // initializing an app with express

                [....] the rest of the code

                // Add a new message
                app.post('/messages', async (req, res) => {
                    let { message, nickname } = req.body;
                
                    if (!message || typeof message !== 'string') {
                        return res.status(400).json({ error: 'Invalid message' });
                    }
                
                    // Default nickname to "Untitled" if missing or not a string
                    if (!nickname || typeof nickname !== 'string' || nickname.trim() === '') {
                        nickname = 'Untitled';
                    }
                
                    try {
                        const data = await loadMessages();
                        const messages = data.messages || [];
                
                        // Ensure no more than 5 messages
                        if (messages.length >= 5) {
                            messages.shift(); // Remove the oldest message
                        }
                
                        // Add new message object
                        messages.push({ nickname, message });
                
                        await saveMessages(messages);
                        res.json({ messages });
                    } catch (err) {
                        console.error('Error adding message:', err);
                        res.status(500).json({ error: 'Error adding message' });
                    }
                });
                
            
        

In this code, when making a POST request to the /messages endpoint the 'app.post' method (fancy word for built in function) is called and saves the message in a json file.


4. Here is what the .json file looks like!

            
                // messages.json

                {
                    "messages": [
                      {
                        "nickname": "mynickname",
                        "message": "my gr8 message"
                      }
                    ]
                  }
            
        


5. Finally, a GET request is made on the /messages endpoint, which returns the messages contained in our .json file!

        
            // script.js

            [...] the rest of your code


            // The function that loads messages 
            function loadMessages(){
                fetch('/messages',
                {
                  method: 'GET',
                  headers: {
                    'Content-Type': 'application/json',
                  }
                })
            }

            // calling the function when the page loads
            loadMessages()


            ---------


            // app.js

            [...] the rest of your code

            // Get all messages
            app.get('/messages', async (req, res) => {
                try {
                    const data = await loadMessages();
                    res.json(data);
                } catch (err) {
                    console.error('Error reading messages:', err);
                    res.status(500).json({ error: 'Error reading messages' });
                }
            });
        
    

Click to make a GET request is made to the /messages endoint our backend (aka API) sends all the saved messages back.



Messages

i dare you to press the GET request button :3



Don't know what to build or the concept of backend is still blurry for you? Here are some examples/use cases!



Don't like any of these, have an AI generate a list of three ideas for you to start working on!

ideas... thought... help me with AI



That's it! you should definitely send a message in the #athena-award channel if you have questions OR checkout the resources page for additional details :3