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

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");
});

Related

TypeError: Cannot read property 'myemail' of undefined

I am trying to make login system using html,nodejs,express.
I have created a form and gave the input tag name as myemail, I used this name just to display email in console.But I am getting this error.
I have checked all the answers provided in the similar questions, but none of them worked for me.
app.js
const express = require('express');
const path = require('path');
const session = require('express-session');
const bodyparser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
const router = require('./router');
const bodyParser = require('body-parser');
app.set('view engine','ejs');
app.use('/static',express.static(path.join(__dirname,'public')));
app.use('/assets',express.static(path.join(__dirname,'public/assets')));
app.use('/route',router);
app.use(bodyparser.urlencoded({extended:true}));
app.use(bodyparser.json());
app.use(session({
secret:'secret',
resave:'false',
saveUninitialized:'true'
}));
app.get('/',(req,res) =>{
res.render('base',{title:'Login'})
})
app.listen(port,console.log("listening.."));
router.js
const express = require('express');
const router = express.Router();
const user = {
email : 'abc#gmail.com',
password : 'abcd'
};
router.post('/login',(req,res)=>{
console.log(req.body.myemail);
res.end("Login Successful");
});
module.exports = router;
base.ejs
<%- include('header') -%>
<div class="div text-center center-div" id="login">
<div class="container w-25 border py-5">
<div class="title pb-5 ">
<h2 class="font-weight-bold">Login System</h2>
<span>Login for the existing user</span>
</div>
<form action="/route/login" method="POST"class="pt-0">
<div class="form-group">
<input type="email" class="form-control" placeholder="Email Id" name="myemail">
<small class="form-text text-muted">Register Email address</small>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="mypassword">
</div>
<button type="submit" class="btn btn-success rounded-pill">Submit</button>
</form>
</div>
</div>
<%- include('footer') -%>

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.

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

Post form data in route in node js

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 }));

Categories