Post form data in route in node js - javascript

When I post form data to routing then, getting a undefined parameter error. I can't to send the form parameter to routing file. Please help me. Here is my code with files name
Getting Error
TypeError: Cannot read property 'username' of undefined
node.js
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.route('/').get(function(req,res) {
fs.readFile('./html/registers.html',function(err,data) {
res.writeHead(200,{'Content_type':'text/html'});
res.write(data);
res.end();
});
});
app.post('/formData', function(req, res) {
var username = req.body.username;
var password = req.body.password;
console.log("post received: %s %s", username, password);
});
register.js
<form action="formData" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter username" name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

Please replace the following
<form action="formData" enctype="multipart/form-data" method="post">
By
<form action="/formData" method="post">
Before the route function add following
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Related

How can I get a alert saying "Welcome" +username that I entered

So,here's my index.html file which consists of username and password input fields.So,when the user clicks on the submit button I want to get a alert saying "Welcome"+username.Im using nodejs also here. please help me.
index.html
<body>
<main class="form-signin">
<form method="post" action="/">
<h1 class="h3 mb-3 fw-normal">Login</h1>
<br/>
<div class="form-floating ">
<input type="name" class="form-control" name="username" placeholder="Enter Username...">
<label for="floatingInput">Username</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" name="password" placeholder="Enter password">
<label for="floatingPassword">Password</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
</form>
</main>
</body>
Here's my server.js file where all the routes has been handled.
So below here when i click the submit button im getting the value of username entered in post request But how exactly should I create an alert?
server.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.sendFile(__dirname+"/index.html");
});
app.post('/', function(req,res) {
var username=req.body.username;
// I don't know what to do here exactly
});
app.listen(3000,() => {
console.log("Server started on port 3000");
});

Node, Express, vanilla JS POST form not sending data to API

I am using Node JS and Express JS to make a form submission push data to the database.
This is my form
<form action="/pokedex/register/poke_submission" method="POST">
<div>
<label for="name">Pokemon</label>
<input type="text" name="name" id="name" required />
</div>
<div>
<label for="number">Number</label>
<input type="text" name="number" id="number" required />
</div>
<div>
<label for="primaryType">Primary Type</label>
<input
type="text"
name="primaryType"
id="primaryType"
required
/>
</div>
<div>
<label for="secondayType">Secondary Type</label>
<input type="text" name="secondayType" id="secondayType" />
</div>
This is my POST API
app.post("/pokedex/register/poke_submission", async function (req, res) {
const poke = new Pokemon({
information: {
name: req.body.name,
dexNumber: req.body.dexNumber,
primaryType: req.body.primaryType,
secondaryType: req.body.secondaryType, // Not required
});
try {
const newPokemon = await poke.save();
res.send(newPokemon);
} catch (err) {
res.send(req.body);
console.log(err);
}
});
and I am using these two
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
When I hit Submit, it sends me to /pokedex/register/poke_submission but with a 405 error.
It seems it should be as below in code:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

Simple Tutorial code not getting data from a Login form (express js)

So I am following a YouTube Tutorial on how to set up a simple login server (channel name: web dev simplified, video: "Node.js Passport Login System Tutorial")
The code (at the stage I am at # 14:12 mark in video) is suppose to console-log an array of a new registered user at the terminal.
but I get an empty array instead. Despite having the same code (I followed him step by step) I do not get the new user. What am I doing wrong?
const path = require('path');
const fs = require('fs');
const express = require('express');
const app= express();
const bcrypt = require('bcrypt');
const session = require('express-session');
// Get express ready to setup server
var users =[];
//{id:"", name:"", email:"", password:"",}
app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }));
// Sets up main page
app.get('/', (req, res) => {
res.render('index.ejs', {name: 'Moe'})
})
////////////////Sets up login page////////////////////////
app.get('/login', (req, res) => {
res.render('login.ejs')
})
///////////////Sets up register page////////////////////////
app.get('/register', (req, res) => {
res.render('register.ejs')
})
///////////////////// Recieves date from register /////////////////
app.post('/register', async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
res.redirect('/login')
} catch {
res.redirect('/register')
}
console.log(users);
});
///////////////////////////////////////////////////////
// Setup Server
app.listen(5000);
html for login
<h1>Login</h1>
<form action="register" method="post">
<div>
<label for="name">username</label>
<input type="text" id="name" name="name" required>
</div>
<br>
<div>
<label for="name">password</label>
<input type="text" id="password" password="password"required>
</div>
<br>
<button type="submit">Login</button>
<br>
Register
</form>
<br>
back to Homepage
html for register
<h1>register</h1>
<form action="register" method="POST">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
</div>
<br>
<div>
<label for="email">email</label>
<input type="email" id="email" name="email" required>
</div>
<br>
<div>
<label for="password">password</label>
<input type="password" id="password" password="password"required>
</div>
<br>
<button type="submit">Register</button>
<br>
Login
</form>
<br>
back to Homepage
The request body needs to be parsed. Add this above your routes:
app.use(express.json());
^^^ Scratch this part. It's only needed with a JSON payload ^^^
In your html you have password="password" instead of name="password" for the password input element.

How to get data from form and add inputs to Mysql table.Using JQuery

I'm trying to add input from HTML page to Mysql, I don't know what is wrong with my code. Why my input data from the form is not adding in MySQL database table? I already created a table in Mysql, but not able to insert values.
<form action="/data" method="post">
<div class="form-group">
<label for="exampleInputName">🙏 Name</label>
<input type="text" class="form-control" id="exampleInputName" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="exampleInputEmail"> 📩 Email Address</label>
<input type="email" class="form-control" id="exampleInputEmail" placeholder="Enter Email">
</div>
<div class="form-group">
<label for="exampleInputcontactnumber"> 🔢 Contact number</label>
<input type="number" class="form-control" id="exampleInputcontactnumber" placeholder="Enter Contact number">
</div>
<div class="form-group">
<label for="exampleInputRestaurantName">🍽 Restaurant Name</label>
<input type="text" class="form-control" id="exampleInputRestaurantName" placeholder="Enter RestaurantName">
</div>
<div class="res mt-5 mb-5 text-center" >
<input type="submit" value="Submit" id="startapp" class="btn btn-primary" ></a>
</div>
</form>
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var con = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'password',
database :'mydb'
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
app.set('view engine', 'ejs')
app.get('/', function (req, res) {
res.sendFile(__dirname + '/Register.html');
});
app.post('/data', function(req, res){
connection.query(sql , function(err, result){
var sql = "INSERT INTO customers (Name,Email,ContactNumber,RestaurantName) VALUES (" + req.body.exampleInputName + "', '"+req.body.exampleInputEmail +"','"+ req.body.exampleInputcontactnumber +"','"+ req.body.exampleInputRestaurantName +"')";
if(err) throw err;
console.log("Data added");
});
res.send(data);
});
con.end();
app.listen(3000, function () {
console.log('App is running on port');
});
In you query you have an insert for a single column but you have values for 4
you also miss the single quote at the begin of the values so if you want insert a single column you should use
var sql = "INSERT INTO customers (Item)
VALUES ('" + req.body.exampleInputName +"')";
if(err) throw err;
console.log("Data added");
});
if you want insert value for 4 columns you should
var sql = "INSERT INTO customers (your_col_name, your_col_email, your_col_contact, your_col_resturant)
VALUES ('" + req.body.exampleInputName + "', '"+req.body.exampleInputEmail +"','"+ req.body.exampleInputcontactnumber +"','"+ req.body.exampleInputRestaurantName +"')";
if(err) throw err;
console.log("Data added");
});

Call app.use/app.post (which INSERT INTO a db) to get form values

I created an app.use with express in order to INSERT values in a database. I want to get those values when user clicks register.
My form:
<form class="form-signin" method="POST">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<label for="inputEmail" id="lblEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email
address" name="email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control"
placeholder="Password" name="passworf" required>
<label for="repeatInputPassword" class="sr-only">Repeat Password</label>
<input type="password" id="repeatinputPassword" class="form-control"
placeholder="Repeat Password" required>
<label for="name" class="sr-only">Name</label>
<input type="name" id="inputName" class="form-control" placeholder="Name"
name="name" required>
<label for="surname" class="sr-only">Surname</label>
<input type="surname" id="inputSurname" class="form-control"
placeholder="Surname" name="surname" required>
<div class="checkbox mb-3">
</div>
<button class="btn btn-lg btn-primary btnblock-"
type="submit">Register</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
</form>
app.use used in order to insert values in the database. Am using MySQL below:
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var http = require('http');
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.use('/', urlencodedParser, function(req,res, next){
var adminUser = req.body.email;
var adminPass = req.body.password;
var adminName = req.body.name;
var adminSurname = req.body.surname;
console.log(req.body);
var sql = "INSERT INTO admins VALUES(null, ?, ?, ?, ?) ";
con.query(sql, [ adminUser, adminPass, adminName, adminSurname],
function(error, rows, fields){
if(!!error) {
console.log('Query Failed' + error.message);
} else {
console.log('Query Successful');
console.log(rows.insertId);
next();
}
});
})
app.listen(5500);
You need to create a Express POST route that the form can post too.
app.post('/', function (req, res) {
// Process form here
var adminUser = req.body.email;
var adminPass = req.body.password;
var adminName = req.body.name;
var adminSurname = req.body.surname;
// etc.
});
The path should match the form action attribute
Your form must be sending the POST request to the same route that you defined with app.use(...). In this case, your form is POSTing to the same route it is on, which means it needs to be on the / route to work.
Change your app.use(...) to be app.post(...) so that it only handles POST requests, then serve the form's html from the same route using:
app.get('/', function(req, res) {
res.sendFile(path-to-form);
})
See: https://codesandbox.io/s/won9jzj8k7

Categories