I attempted to utilize body-parser, but it appears that it is not functioning properly

I am having trouble with body parser and express as it is not functioning properly. When I print req.body in the console, it returns an empty object.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine','ejs');

app.get('/' ,function(req,res){
var name = "ganesh"
console.log(req.body.name);
res.render('home',{name : name});
});

app.post('/postname' , function(req,res){
res.redirect("/");
});

app.listen(3000,function(){
console.log("server started");
};

This is the content of my home.ejs file:

<html>
<head>
    <title>practice</title>

</head>
<body>
    <h1>
        hello<%= name %> This is the home page
    </h1>
    <form action="/postname" method = "POST">
        <input type = "text" name="name">
        <button>
            go
        </button>
    </form>
</body>

I have ensured that body-parser, ejs, and express are installed correctly.

The following is printed in the console:

Server started {}

Answer №1

When you redirect the postname request to /, it's important to remember that the request data will not be forwarded to the / root route.

The use of res.redirect("/") will result in a response being sent back to the client with a status code of 302. Following this, the client will make a Get request to the / route without any accompanying data. As a result, the request.body will always be empty in a Get request.

If you wish to pass on the data from the postname route to the / route, you can do so by including it in the query string.

For example:

var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
    var name = "ganesh"
    res.render('home', { name: req.query.name });
});
app.post('/postname', function (req, res) {
    var name = "ganesh"
    console.log(req.body.name);
    // handle the post data here 
    res.redirect("/?name=" + req.body.name);
});
app.listen(3000, function () {
    console.log("server started");
});

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

Best Practices for Showing JSON Data from MongoDB in an Angular Material Table

Desire I'm trying to extract data from MongoDB and exhibit it in an Angular Material Table. Problem Even though I can view the results of my MongoDB query in the console/terminal, the Chrome browser console indicates that my JSON data has been save ...

Encountering an issue with the for loop in React Native when using FlatList

As a beginner in programming, I am eager to dynamically render a list. The Navbar parent component holds the state with different Food Types categories such as Mexican and Chinese, each with its corresponding menu. My goal is to display each Food Type fol ...

Applying conditional statements to an array's parent elements during iterations in JavaScript

Here is my complete script for relevance. I am currently looping through an array from a JSON object and populating content into an HTML div based on the content's ID. The process works well, but I am facing an issue with the logic related to the par ...

delivering the optimized main RequireJS file as a static asset through NGINX servers

Is it true that serving static assets from NGINX or another server is better than using your Node.js application server? In my case, I have a single-page application where in production mode, only one optimized .js file is served from the index page, and ...

Angular JS Integration with PapaParse

Currently enjoying the efficiency of PapaParse's CSV parsing and unparsing features. Interested in integrating this with Angular JS - anyone able to assist with this integration? Excited about incorporating PapaParse into an Angular environment. Work ...

Utilizing JavaScript to implement conditional if-else statements on CSS properties

I am trying to implement conditions on CSS properties in JavaScript. What is the most efficient approach to achieve this? <html> <head> <title>TOOLTIP USING JAVASCRIPT</title> <style> span{ curso ...

Pass a variety of data points to PHP using Ajax requests

I am facing a challenge with passing multiple parameters during Ajax calls. The code works perfectly when I only pass one parameter. Here is the code snippet for the Ajax call: $.ajax({ type: "POST", url: "dataCartas.php", ...

Getting numerous MongoDB records with identical attributes by means of Express

I am attempting to retrieve all MongoDB entries associated with a specific username using Express. Here is the code I have written: transcriptRepository.getTranscriptByUsername = (username) => { return Transcript.find({ username }) .then( tran ...

Split an array of articles into subarrays according to their topics using the reduce method in Javascript

I am currently seeking a solution to divide an array of articles into subarrays based on the first key-value pair and its order. After researching several Stack Overflow posts, I have come across one that seems to align closely with my objective: break a ...

Expanding containers with flexbox to allow for flexibility in size

I need help with a page that contains 3 div elements, where 2 of them need to be resizable. These elements should be able to be moved left or right, and maximized or minimized. You can view the example on Stackblitz. The issue I'm facing is that som ...

Having trouble getting JQuery Ajax POST to work in Codeigniter

Encountering an issue with jQuery AJAX post in CodeIgniter, where clicking the submit button triggers an error. Below is the code snippet: home.js form.on('submit', function(e){ e.preventDefault(); var fields = {}; form.find(' ...

Changing an HTML table into an array using JavaScript

Is it possible to transform an HTML table into a JavaScript array? <table id="cartGrid"> <thead> <tr> <th>Item Description</th> <th>Qty</th> <th>Unit Price</th> ...

What could be the reason why my JavaScript code for adding a class to hide an image is not functioning properly?

My HTML code looks like this: <div class="container-fluid instructions"> <img src="chick2.png"> <img class="img1" src="dice6.png"> <img class="img2" src="dice6.png" ...

Running pug directly from the local node_modules directory

I'm currently attempting to run pug (/jade) from my node_modules directory, however I am unable to locate the executable within the node_modules/.bin folder. I am running MacOS 10.12.5 and installed pug using the "npm install --save pug" command. Is ...

Tips for efficiently sending multiple ajax requests

Seeking help with my ajax knowledge. Currently, I have a function that is supposed to insert multiple items into an SQL database using a PHP page. However, it seems to only be inserting the last item entered. Here's the code snippet: function submitI ...

JSFiddle Functioning Properly, But Documents Are Not Loading

My JSFiddle is functioning properly, but the files on my computer aren't. It seems like there might be an issue with how they are linking up or something that I may have overlooked. I've checked the console for errors, but nothing is popping up. ...

Searching for a table element and clicking it based on its text with Protractor

<tr id="item" ng-repeat="item in itemList> <td id="code" ng-repeat="column in columns">Different Text</td> </tr> I have encountered some similar issues before, but I am still struggling to find a solution. Here is what I have at ...

Ways to personalize the get function using various queries in Express.js on Node.js!

I'm currently in the process of creating a RESTful API using Node.js and Express.js, although I am still fairly new to this technology. The code below outlines the get method for retrieving a list of councils stored in MongoDB. const { Council } = re ...

Tips for transferring an array between two applications using AngularJS

I have two applications, appA for front end and appB for admin end. In appA, I am building an array called queries using a service through a controller. However, when I try to retrieve this array list in a controller in appB, it appears empty. Everytime ...

Having trouble importing a module in my Node.js/Express application

I've encountered an issue while trying to import files into my node js server file. My usual method is correct in terms of paths, so I'm puzzled about what the error might be. import express from 'express' import mongoose from 'mon ...