Getting input data from text field in Nodejs

Related searches

I'm sure this has already been answered but I can't find the exact question I'm looking for.

I have an ejs file that has this for the form.

<form action="" method="POST">
   <div class="input-group">
      <input type="text" class="form-control" name="userSearchInput" placeholder="Enter the id of the product you would like to buy" aria-label="Recipient's username" aria-describedby="basic-addon2">
      <div class="input-group-append">
           <button class="btn btn-outline-secondary" id="searchBTN" type="submit"><i class="fas fa-cart-plus mr-2"></i>Add to Cart</button>
    </div>
 </div>
</form>

On the node side in my app.js file, I've installed and downloaded both express and body-parser and done the requisite require function.

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

I've set up my middleware for body-parser here:

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

Then, to get the content of what the user types into the input text box, I'm using this:

app.post('/', function(req, res) {
    var item = req.body.userSearchInput;
    console.log(item);
});

This is my first time using app.post and since nothing is being console logged- I'm not sure where I'm going wrong.

full app.js file

var express = require('express');
var path = require('path');
var http = require('http');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var nodemon = require('nodemon');


var app = express();

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

// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));

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

// create connection to mySQL db
var connection = mysql.createConnection ({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'bamazon'
});

// initialize connection
connection.connect();

// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
    if (error) throw error;
    console.log(results);
    app.get('/', function(req, res){
        res.render('index', {list: results});
    })
});

app.post('/', function(req, res) {
    var item = req.body.userSearchInput;
    console.log(item);
});


// setting up listen for server function
app.listen(port, function (err) {
    if (err) throw err;
    console.log("Server is running on port " + port);
});

use

<form action="/" method="post">

How to get an input from an HTML textbox and store it in a variable , Synchronous Input. Node.js allows you to run JavaScript code outside of a browser window, offering powerful tools to interact with a computer filesystem, run� 1. Use Node JS Process Object’s Stdin. // Get process.stdin as the standard input object. var standard_input = process.stdin; // Set input character encoding. standard_input.setEncoding('utf-8'); // Prompt user to input data in console. console.log("Please input text in command line."); // When user input data and click enter key.

Firstly add form action in your ejs file like action="/search".Step 2: try with app.post('/search'

Getting User Input in Node.js, We can get the value of text input field using various methods in script. There is a text value property which can set and return the value of the value attribute of a text field. Also we can use jquery val() method inside script to get or set the value of text input field. field, and then click the button below. In this tutorial, You will learn how to insert form data into the table using Node.js & MySQL. Even you will get the standard Node.js Script to use in your project. All the steps will be more helpful for inserting data with Node.js & MySQL. So, Read the complete tutorial with full concentration.

Works fine i just commented out db connections only. may be try this app.js file with new express project. Run command node app instant of npm start

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

// var nodemon = require('nodemon');
// var mysql = require('mysql');

var app = express();

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

// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));

// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/*
 create connection to mySQL db
 var connection = mysql.createConnection({
     host: 'localhost',
    user: 'root',
    password: 'root',
     database: 'bamazon'
 });

// initialize connection
 connection.connect();

// run db query and print items to index html home page
 connection.query('SELECT * from products', function (error, results) {
     if (error) throw error;
     console.log(results);

 });
*/
app.get('/', function (req, res) {
    res.render('index', { list: [], title:"salman" });
})


app.post('/', function (req, res) {
    var item = req.body.userSearchInput;
    console.log(item);
});


// setting up listen for server function
app.listen(port, function (err) {
    if (err) throw err;
    console.log("Server is running on port " + port);
});

How to get the value of text input field using JavaScript , Express, node, and third-party packages on NPM provide everything you need to Objective: To understand how to write forms to get data from users, and Consider a simple HTML form, with a single text field for entering the name The submit input will be displayed as a button (by default)—this can be� Originally Answered: How do I get an input from a html textbox and store it in a variable in NodeJs? You only need to pass form data to a REST url and read the request parameters. Look ExpressJs, its a minimal web framework, with which you can easily handle these kind of things.

Express Tutorial Part 6: Working with forms, displaying an empty HTML form in response to an initial GET request; user submitting Handling form data also comes with extra security considerations. <textarea class="input" id="message" name="message" rows="4"� The question is asking how to pass a user entered form in a HTML document to a Node.js server. See Roger Le's answer to How do I pass a user-entered form value from HTML to Node.js? to correctly make your HTML.

Forms, File Uploads and Security with Node.js and Express, Sets or returns whether a text field should automatically get focus when the page loads: defaultValue: Sets or returns the default value of a text field: disabled: Sets or returns whether the text field is disabled, or not: form: Returns a reference to the form that contains the text field: list: Returns a reference to the datalist that

The Author date of death and date of birth fields and the BookInstance due_date field are the wrong format to input into the date input field on the form (it requires data in form "YYYY-MM-DD"). The easiest way to get around this is to define a new virtual property for the dates that formats the dates appropriately, and then use this field in

Comments
  • this form is rendered from app.get('/') route? I mean current link is root?
  • yes. there is only one html page and that is the root page. the form is on the root page.
  • are you sure you added app.use(bodyParser..) before the defining the routes? if it's true, then try to remove action="" (this means will send post request to same url with current)
  • yes. I'll update my post with my full app.js file
  • why app.get('/') is inside query callback? that doesn't make sense to me.
  • didn't work. Didn't console.log the item inputted in either the browser or the CL