Encountering difficulties retrieving form data in NodeJS Express

I'm currently facing an issue with my form where I am trying to fetch data from the server using ejs templating in my node app. Everything seems fine as there are no errors displayed, but unfortunately, I am unable to retrieve the data in the console.

Here is a snippet of my code:

server.js

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

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');

const port = process.env.PORT || 3000;

const key = process.env.SECRET_KEY;


app.get('/register',(req,res) => {

  res.render('register',{title:'Register here'});
});

app.post('/register',(req,res) => {

  const name=req.body;
  console.log(name);
});

app.listen(port,(req,res) => {

   console.log(`App is running at ${port}`);
});

register.ejs

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27454848535453554657671209170916">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"gt;

<title><%= title %></title>

<style>
  
    h1 {
     text-align: center;
     margin-top:50px; 
     }
     
     .form{
       margin-top:50px;
       margin-left:30%;
       margin-right:30%;
     }
     
     button{
        margin-top:20px;
     }

</stylegt;

</headgt;
<body class="container"gt;

<h1><%= title %></h1gt;

<div class="form"gt;

    <form action='/register' method='POST'gt;

    <input name="nam" class="form-control" type="text" placeholder="Name" aria-label="default input example"gt;
    <button type="button" class="btn btn-primary"gt;SUBMIT</buttongt; 
    
    </formgt;

</divgt;

 <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="583b372a3d186a7661766a">[email protected]</a>/dist/umd/popper.min.jsgt; integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8pgt; crossorigin="anonymousgt;

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33515c5c47404741524373061d031d02">[email protected]</a>/dist/js/bootstrap.min.jsgt; integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtTgt; crossorigin="anonymousgt;

</bodygt;
</htmlgtgt; 

If you have any insights into what might be going wrong in the provided code or suggestions on how to correct it, please feel free to share.

Answer №1

If you want to submit a form, make sure to specify the button as a submit button. Using type="button" will only act as a regular button and not submit the form.

To correct this issue, follow these steps:

<button type="submit" class="btn btn-primary">SUBMIT</button>

By setting the button type as submit, clicking it will now trigger the submission of the form it is contained in!

Answer №2

Implement the following code in your Nodejs post request:

const username = req.body.username;

Additionally, update this line of code:

<input type="submit">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the node version using the n library does not affect the npm version

I'm trying to sync my npm version with my node version, but no matter which node version I update to using the n library, the npm version remains stuck at 8.19.2. This is happening on my MAC running Monterey OS. ...

Leveraging webpack for requiring modules in the browser

I've been attempting to utilize require('modules') in the browser with webpack for the past couple of days, but I could achieve the same functionality with browserify in just 5 minutes... Below is my custom webpack.config.js file: var webp ...

How can I modify the default database setting in MongoDB from 'test' to something else?

mongoose.connect(process.env.DATABASE_URL, {useNewUrlParser: true}); const MyModel = mongoose.model(mymodel, new Schema({ name: String })); I have set up a database named 'test' with a collection named 'mymodel'. Could you guide me on ...

Encountering errors: Time-zone discrepancies arise when making API calls from AngularJS and querying results from Firebase using NodeJS

Whenever I try to query with a date range, the results returned are incorrect. I have implemented DateRangePicker jQuery for selecting both date and time ranges. After that, I make an API call and send my date/Moment JS object to my Node.js API where I q ...

Error during installation of broccolil-closure-compiler

Currently, I am testing the es-6 promise-polyfill. During the testing process, one of the required node packages is broccoli-closure-compiler, which unfortunately is not installing. I suspect that the issue may be related to being behind a proxy server. Ho ...

Customized information based on user agent using Node.js

I am looking to create my Node.js application to cater to various user agents such as Web, iOS, and Android, each requiring different data (e.g., filter fields specific to certain user agents). Should I create separate routes for each user agent or imple ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

Closing the React Material UI drawer with nested list items upon clickingORClicking on nested list

Currently, I am encountering an issue with my React project that utilizes Material-UI. The problem arises when I incorporate nested list items within the drawer component. Previously, everything was functioning smoothly until the addition of these nested i ...

Guide to utilizing Gatsby for showcasing a directory containing images and markdown files

Being new to Gatsby, react, GraphQL, and more unfamiliar technologies, I have primarily relied on pure CSS, HTML, and JavaScript for my website projects in the past. However, intrigued by the potential of Gatsby, I decided to step out of my comfort zone an ...

Performing Batch Writes in Firestore using the Admin SDK

I have a massive ASCII flat file containing 1.5 million lines, which is essentially a list of parts from a manufacturer. I want to store this data in Firestore. Originally saved as a .csv file, the size was 250GB. After converting it to a JSON file using ...

Tips for verifying if a specific user is logged in with Passport

I need to restrict access to a specific link ('New Blog') so that only users with the username "admin" can see it. I attempted to use an if statement but it seems to be causing an error: <% if(currentUser.username = "admin") { %> & ...

Utilize Jest to mimic module functions within a different module

Looking for assistance with Jest as a newcomer, I am attempting to write tests for existing code. While there are numerous resources on mocking functions within modules using Jest, I feel like I'm dealing with a more complex or perhaps foolish scenari ...

Error encountered when attempting to utilize a variable within an EJS template document

I seem to be encountering some difficulties while attempting to get an EJS template file to recognize a variable that holds the rows from an SQLite3 table query in a related .js file. Whenever I try to access that route by launching the server, I receive a ...

The Selenium Docker video fails to function when the network mode is set to 'host' in the Docker Compose configuration

The docker-compose file is configured with a chrome-standalone image and another node (named test) as the test runner. The Cloudbuild.yaml file triggers the test, which works successfully. Below is the docker-compose file: version: "3" services: ...

Understanding NPM Fundamentals and Installing Packages Locally

I am not very familiar with using Node and I have a question that may seem trivial to some, but I cannot find clear documentation on it. My limited skills in Node prevent me from investigating this further. I am currently following the instructions provid ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Combining/naming PM2 applications

Looking at the PM2 configuration located at /home/foo/someconfig.json { "apps": [ { "name": "foo-main", "script": "./index.js", }, { "name": "foo-bar", "script": "./bar.js" ...

What sets apart a string constant from a string enclosed in quotation marks? And what techniques exist to transform one into the other?

Calling an asynchronous function: const variable = 'something' await MyAsyncFunction.execute(variable) No output is displayed. But if I change it to: await MyAsyncFunction.execute('something') It works!! Can someone please explain h ...

Unable to locate module within the ngModule imports

I am facing a peculiar issue. I have used npm install to add ng-push, imported PushNotificationsModule from 'ng-push', and included PushNotificationsModule in my ngModule imports. Interestingly, both the ng build and ng build --prod commands are ...

Implementing a rate limit on the login API that is specific to individual IP addresses rather than being

I have successfully implemented the [email protected] module, but I am facing an issue where it is blocking the API globally instead of for a specific API that is receiving hits. This is my current code: const limiter = new RateLimit({ windo ...