jwdrzv
jwdrzv

Reputation: 33

Simple way to receive form data from an html <form> tag

I haven't been able to find a solution for simply receiving the data from an html form, and logging it to the console. What am I missing?

Here's my html code:

<!DOCTYPE html>
<html>
   <head>
      <title>User Login</title>
      <link rel="stylesheet" type="text/css" href="login.css">
   </head>
   <body>
      <div class="login_wrapper">
         <div class="login_box">
            <h1>User Login</h1>
            <form id="login_form" method="post" action="/">
               <p id="username">Username</p>
               <input type="text" name="username" placeholder="Enter Username">
               <input type="submit" name="" value="Login">
            </form>
         </div>
      </div>
   </body>
</html>

And my server side code:

var express = require('express');
const bodyParser = require("body-parser");

var app = express();

// middleware/routing
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(request, response) {
    response.sendFile(__dirname + "/public/login.html");
});

app.post("/", (response, request)=>{
    console.log(request.params.username);
    // console.log("HI");
    response.end();
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

The error I keep getting when clicking the login button is: TypeError: Cannot read property 'username' of undefined

I just want to log whatever was entered in the input field for username (I suppose it's a JSON object?).

Upvotes: 3

Views: 82

Answers (1)

Hardik Tewari
Hardik Tewari

Reputation: 113

The problem lies in the order of request, response parameters. The order is reversed in your code.

Additionally, you have to use request.body to access the form fields posted.

Below is the modification you need for the POST handler. Hope it helps.

app.post("/", (request, response)=>{
    console.log(request.body.username);
    // console.log("HI");
    //response.end();
});

Upvotes: 1

Related Questions