why node.js bodyParser always returns 'undefined'? - node.js

In 'app.js' I have
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
'index.js' full codes
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Here' });
});
router.post('/manager', function(req, res, next) {
var connection = mysql.createConnection({
host : 'localhost',
user : req.body.username,
password : req.body.password,
database : 'shops'
});
connection.connect(function(err){
if(!err)
res.render('manager', { title: 'Here' });
else
console.log("Error connecting database ...");
});
});
module.exports = router;
In 'index.html' login form
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' type='text'><br>
Password<br>
<input id='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>
In index.js line 12-13
req.body.username
req.body.password
Everytime I try to parse data from html form, they return 'undefined'. I'm new to node.js scripting. Am I doing something wrong?

You're missing name attributes on your <input> tags. Add them like:
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' name='username' type='text'><br>
Password<br>
<input id='password' name='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>

Related

Body parser returning undefined for req.body request (SIMPLE LOGIN for beginner)

So I installed body parser via
npm i install express body-parser
and I wrote a simple code designed to input a user into an array after they complete a registration form.
but when I console.log the user it returns undefined for both email and password
here is the server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const PORT = 3000;
var Users = [{"email":"mike#gmail.com", "password":"456"}];
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/Register.ejs', (req, res) => {
res.render('Register.ejs')
})
app.post('/views/Register.ejs', (req, res) =>
{
const newUser = {
email: req.body.email,
password: req.body.password
};
Users.push(newUser);
res.json(req.body.email);
console.log(Users)
}
)
app.listen(PORT);
here is the html for the register page
<h1>Please Register</h1>
<body>
<form action="/views/Register.ejs" method="POST">
<div class="div">
<label for="email">Enter Email</label>
<input type="email" id="email"for="email" id="email" required>
</div>
<div class="div">
<label for="password">Enter new password</label>
<input type="password" for="password" id="password" required>
</div>
<button type="submit"> Register </button>
</form>
</body>
Only installing body-parser is not enough. You have to put them in the code as middleware.
Top of the code use:
var bodyParser = require('body-parser');
and then use the code in somewhere middle of the code:
app.use(bodyParser.json())

How to move from one route to other in node.js

I have form post job.html and a button post. I want that when someone submits this form the values save in database and then i get these values on another helper's feed.html page. Right now, my values are saving in database but i am unable to understand how to get those values in next page.
This is the part of html code for helpers feed.
<div class="col-md-10" >
<div> Description:
<input type="text" id="desc" name="budget"class="form-control">
<div>
<div> Category:
<input type="text" id="category" name="budget" class="form-control">
</div>
<div > City:
<input type="text" id="city" name="budget" class="form-control">
</div>
<div > Budget
<input type="text" id="budget" name="budget" class="form-control">
</div>
This is node.js file. post.js
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'sahoolat1',
database : 'fyp_sahoolat'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
var app = express();
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/job post.html'));
});
app.post('/post',(request,response,next)=>{
var description=request.body.description;
var contact_number=request.body.contact_number;
var city=request.body.city;
var budget=request.body.budget;
var category=request.body.optradio;
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
console.log("moving");
});
next();
});
app.get('/post',(request, response) => {
connection.query("SELECT * FROM jobs",(err, result) => {
if(err) {
console.log(err);
}
else {
console.log(result);
res.send(result);
}
});
});
app.listen(3000);
The code runs fine till the line where i am saving in database and it prints "moving" on console.
I want to get each field value in the respective text fiels(as shown in screenshot)

Browser waiting on localhost on POST request

I'm building a website, and i have a registration form where i need to submit a form via POST, and register a user in a mongoDB databse. The website works fine so far, but when i submit the registration form the browser just "waits for localhost" forever. I use EJS as my templating engine, although i don't think that matters.
register.ejs:
<% include partials/header %>
<%include partials/nav %>
<h1>REGISTER</h1>
Login
<form id="registerForm" action="/register" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
<small id="passwordHelp" class="form-text text-muted">Your password must be at least 8 characters long.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<% include partials/footer %>
app.js:
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
passport = require("passport"),
bodyParser = require("body-parser"),
User = require("./models/user"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose");
//Set up MongoDB
var mongo = require("mongo");
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/customerapp';
//MongoJS
var mongojs = require("mongojs");
var db = mongojs("customerapp", ["users"]);
//Mongoose
var mongoose = require('mongoose');
mongoose.Promise = global.Promise
mongoose.createConnection("mongodb://localhost:27017/customerapp");
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "wah wah wah",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
var index = require("./routes/index");
var about = require("./routes/about");
var login = require("./routes/login");
//var register = require("./routes/register");
app.all("index", index);
app.all("about", about);
app.all("login", login);
//app.all("register", register);
// AUTH Routes
//Register get request
app.get("/register", function(req, res) {
res.render("register");
});
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username}),
req.body.password,
function(err, user) {
if(err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/secret")
})
});
});
app.listen(process.env.PORT || 3000, process.env.IP, function () {
console.log('Example app listening on port 3000!')
})
You are using three params instead of two, use it like this.
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username,
password: req.body.password
}),
function(err, user) {
if(err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/secret")
})
});
});
Check to make sure your versions of mongoDB and mongoose are compatible. You can find a compatibility chart here.
In addition to checking your MongoDB and mongoose versions, you should also check if it's actually connecting to the database by using a callback function when you connect to the server, like so:
//Connecting to database using mongoose.connect with a callback
mongoose.connect("mongodb://localhost:27017/customerapp", function(error) {
if(error) {
console.log("There was an error connecting to MongoDB.");
console.log(error);
} else {
console.log("Successfully connected to MongoDB!");
}
});
This callback may also work with mongoose.createConnection instead of mongoose.connect, but I haven't tried. If neither message prints to the console, then the app is not getting any response from the server, not even an error.
For some reason, as long as mongoDB is running at all, GET requests still seem to work even if the connection attempt hangs, but POST requests run into trouble.
Source: Mongoose never connects to mongodb

Why am I getting a HTTP 400 error?

I found that the 400 HTTP error is something with syntax but I cannot find anything wrong with my syntax, could someone help take a look at it?
<!- My form view-->
<h3>Login</h3>
<form action="/home/login" method="post">
Enter your usernmae: <input type="text" name="user" value=""><br>
Enter your password: <input type="password" name="pwd" value=""><br>
<input type="submit" name="enter" value="Enter">
</form>
//controller added to my app.js
app.use('/home', indexController);
//in router.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
router.post('/login', passport.authenticate('local'), function(req, res) {
req.session.save(function (err) {
if (err) {
return next(err);
}
res.redirect('/home/' + req.user.user);
});
});

how to connect html page with nodejs

Iam not able to get the html page.My nodejs is connecting with mongodb but when iam getting values from html page the values are not storing in db.Iam not able establish the connection from frontend to db at a time.help me out
this is my login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form action="/" method="POST">
<center>
User Name: <input type="text" name="username"> <br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
and this is my login.js code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/logindb';
var loginSchema = mongoose.Schema({
username: String,
password: String
});
mongoose.connect(url);
app.get('/login.html', function(req, res) {
res.sendFile(__dirname + "/" + "login.html");
})
app.post('/', function(req, res) {
var Book = mongoose.model('book', loginSchema);
var book1 = new Book({
username: req.body.username,
password: req.body.password
});
book1.save(function(err) {
if (err) throw err;
console.log("Login saved succesfully");
res.end('success');
}
);
});
app.listen(8000, function() {
console.log("Server is running!");
});
For using req.body.username you need to use body-parser module,
install: npm install body-parser -S
Code:
var express = require('express'),
app = express(),
bodyparser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Resources