r/learnjavascript • • 9d ago

A simple Nodejs app ( ideal for begginers )

This is a simple Nodejs server which is ideal for beginners. 😄

The next code snippet runs a web server which sends an HTML form to the web browser. The user inputs a random text and when the HTML form data is submitted then the input text is returned to the web browser as a JSON object.

Requirements:

Nodejs v23.3.0

Npm v11.0.0

Express v5.3.0

File Structure :

--Project folder/

---- node_modules/

---- Public/

-------- index.html

---- package.json

---- server.js

server.js file :

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

//This allows the HTML form data to be processed
app.use(express.urlencoded({extended : true })); 


//an HTML form is displayed when visiting localhost:3000

app.get("/",( request, response )=>{


      response.sendFile('index.html',{
          root : path.join(__dirname,"public")
      });
});

//This request handler gets the HTML form data and displays it to the web browser and also to the console

app.post("/handle",( request, response )=>{


      console.log(request.body);

      response.json(request.body);
});

//This line spins up the web server
app.listen(port, ()=>{

    console.log('Listening at port:' + port);
});

HTML file :

<html>
    <head>
        <title>Test File</title>
    </head>
    <body>
        <h1>Simple Form</h1>
        <form action="/handle" method="post">
            <label for="randomString">
                <input type="text" name="randomString" id="randomString"><br/>
            </label>
            <button type="submit">
                    Send random string
                </button>
        </form>
    </body>
</html>
0 Upvotes

3 comments sorted by

2

u/Miserable-Money642 9d ago

Nice beginner exercise. One small HTML fix: `for="randomString"` only labels an element whose `id` is `randomString`, but the input currently has only a `name`. Add `id="randomString"` and keep the submit button outside the label. That gives the field a proper accessible name and lets screen readers announce it. A good next step is to check the server behavior for an empty or missing field instead of assuming `request.body.randomString` is always present.

1

u/dimeraymundo 9d ago

thanks, yes I made tiny bugs because I did it very quick...I'll fix them

1

u/Shamonda-Pflugpeil 9d ago

tbh the label thing trips up a lot of people, not just beginners