"How to resolve req.body undefined in Node JS " - javascript

I am setting up a node js server and in my output of req.body i keep getting undefined, i am trying to requesting SQL data from a form Get request
I am able to retrieve other queries just none involving req.body
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.static(__dirname + '/public'));
app.get('/submit',urlencodedParser,function (req, res){
connection.connect(function (err) {
if (err) throw err;
console.log(req.body.lname);
var exist = req.body.lname;
var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";
connection.query(sql, function(err,result) {
if (err) throw err;
console.log(result);
console.log(exist);
console.log(req.body.lname);
console.log("hello");
console.log(result);
});
});
'
output:
undefined
[]
undefined
undefined
hello
[]

Get request doesn't carry the req.body object.
You will have to use either req.query or req.params to pass your data or transform your get into post.
app.post('/submit', function(req, res) {
connection.connect(function (err) {
if (err) throw err;
var exist = req.body.lname;
var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";
connection.query(sql, function(err,result) {
if (err) throw err;
else console.log(result);
});
});

Related

getting errors The POST method - js

what's the fault in this code
const express = require('express')
const app = express()
const port = 3000
var mysql = require('mysql');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var md5 = require('md5');
//MySQL Connection
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "school"
});
con.connect(function(err){
if(err) throw err;
console.log("Connected!");
});
app.use(bodyParser.json()); //support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); // support encoded bodies
app.get('/', (req,res) =>{
con.query("SELECT * FROM users", function(err, rows, fields){
if(err) throw err;
res.send("The first user is: " + rows[0].email);
});
});
app.post('/', function(req,res){
con.query("SELECT * FROM users WHERE name = ? AND password = ?" , [req.body.name, md5(req.body.password)] , function(err, result, fields){
if(err) throw err;
if(result.length > 0){
if(result)
res.send({ status:1, message: result});
} else{
res.send({ status:0, message: "error in username or password"});
}
});
});
app.listen(port, () => console.log('Example app listening at http://localhost:${port}'))
I get this error in cmd every time I use postman to try post:
Error: Illegal argument undefined
at module.exports (C:\\hsoub\\api\\node_modules\\md5\\md5.js:152:13)
at C:\\hsoub\\api\\index.js:50:87
at Layer.handle \[as handle_request\] (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\layer.js:95:5)
at next (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\route.js:144:13)
at Route.dispatch (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\route.js:114:3)
at Layer.handle \[as handle_request\] (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\layer.js:95:5)
at C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:284:15
at Function.process_params (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:346:12)
at next (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:280:10)
at urlencodedParser (C:\\hsoub\\api\\node_modules\\body-parser\\lib\\types\\urlencoded.js:100:7)
what's the problem?

How to get values from GET request in node.js and use it in the POST request

Am new to Node.js and mysql. How can I get the results from GET request and use it in the POST in node.js
For example:
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
user : 'root',
host : 'localhost',
database : '',
password : ''
});
app.get('/get/pension/:empid', function (req, res) {
const empid = parseInt(req.params.empid);
connection.query("SELECT pensionid from pension where empid = ?",[empid], function(error,rows,fields){
if(!error){
console.log('connected inside');
res.send(rows);
}
else {
console.log('error 1' + JSON.stringify(error,undefined,2));
}
});
});
I want to use the pensionid from the GET request and insert into another table.
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
//should it be request.body? const {pension} = request.body
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)",[pension], function(error,rows,fields){
if(!error){
console.log('Added');
}
else {
console.log('error 1' + JSON.stringify(error,undefined,2));
}
});
});
Any help is much appreciated.
Thank you.
You could access the request body of a post request in the req object.
To parse the post body you have to add body-parser package to parse the request body.
First install the body-parser package.
>$ npm i --save body-parser
Then add the the package in your project file.
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // To parse the Json data
And then access your body in req object.
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
const {pension} = req.body;
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)", [pension], function (error, rows, fields) {
if (!error) {
console.log('Added');
}
else {
console.log('error 1' + JSON.stringify(error, undefined, 2));
}
});
});
Full working code:
var express = require('express');
var app = express();
var mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var connection = mysql.createConnection({
user: 'root',
host: 'localhost',
database: '',
password: ''
});
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
//should it be request.body? const {pension} = request.body
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)", [pension], function (error, rows, fields) {
if (!error) {
console.log('Added');
res.status(201).send("added");
}
else {
console.log('error 1' + JSON.stringify(error, undefined, 2));
res.status(500).send('error 1' + JSON.stringify(error, undefined, 2));
}
});
});
Please note that you have to send response in both error and success case.

Accessing a variable that contains MongoDB data outside of a block of code in JavaScript?

In the code below, I'm trying to make it so that the variable "theNames" is available to me in other functions. When I try to access it outside of the current block of code, it comes back as Undefined. I have tried declaring the variable outside of the block of code that it resides in currently, but I get the same result. I am not positive, but I suspect that this might be because the MongoConnect code is being executed later.
var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo");
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("Name saved to database");
User.collection
})
.catch(err => {
res.status(400).send("Unable to save to database");
});
});
listNames = () => {
var url = 'mongodb://localhost:27017/node-demo';
var theNames;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("node-demo");
//Find the first document in the customers collection:
dbo.collection("users").find({}).toArray(function(err, result) {
if (err) throw err;
theNames = result;
console.log(theNames); //This part of the code works as expected.
db.close();
});
});
}
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Here is how I tried to modify the code to achieve the desired result, but in this case, "theNames" comes back as "undefined".
var theNames;
listNames = () => {
var url = 'mongodb://localhost:27017/node-demo';
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("node-demo");
//Find the first document in the customers collection:
dbo.collection("users").find({}).toArray(function(err, result) {
if (err) throw err;
theNames = result;
console.log(theNames);
db.close();
});
});
}
console.log(`Here is a list of theNames: ${theNames}`)

Post Form data to MySQL using Node.js

I am trying to write a simple server.js in Node, that posts form data from my html file, into MySQL. But I am getting a Syntax error. I have posted the code and error below. I'm struggling to resolve this issue.
Error
http://localhost:3000/submit
Error: No default engine was specified and no extension was provided.
at new View (C:\website\node_modules\express\lib\view.js:61:11)
at Function.render (C:\website\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\website\node_modules\express\lib\response.js:1008:7)
at C:\website\index.js:21:9
at Layer.handle [as handle_request] (C:\website\node_modules\express\lib\router\layer.js:95:5)
at next (C:\website\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\website\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\website\node_modules\express\lib\router\layer.js:95:5)
at C:\website\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\website\node_modules\express\lib\router\index.js:335:12)
index.html
<form action="/submit" method="post">
<input id="name" type="text" name="name" placeholder="Type your name...">
<input id="message" type="text" name="message" placeholder="Type message...">
<input class="submit_message" type="submit" value="Send">
</form>
index.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
connection.connect();
app.get('/submit',function(req,res) {
res.render('index');
});
app.post('/submit',urlencodedParser, function(req, res, next) {
console.log(req.body.name);
console.log(req.body.message);
connection.connect(function(err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `users` (`name`,`message`) VALUES ('" + req.body.name + "', '" + req.body.message + "')";
con.query(sql, function(err, result) {
if(err) throw err;
console.log("table created");
});
});
res.render('index', {title: 'Express'});
});
connection.end();
app.listen(3000, function () {
console.log('Listening on port 3000');
});
MySQL database
This is how my database should look like
I have refactored your code, As per question specified. for ex- You need to mention all our static content inside public directory (i.e your index.html), Also you have done syntax error ie- you have written con.query(sql, function(err, result) instead of connection.query(sql, function (err, result), instead of rendering index.html file as you did res.render('index', {title: 'Express'}); its better you send the file to your public/index.html res.sendFile('public/index.html', { root: __dirname }); as specified by #Pogrindis
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.render('index.html');
});
app.post('/submit', urlencodedParser, function (req, res) {
console.log("Im here");
console.log(req.body.name);
console.log(req.body.message);
connection.connect(function (err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `users` (`name`,`message`) VALUES ('" + req.body.name + "', '" + req.body.message + "')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("table created");
});
});
res.sendFile('public/index.html', { root: __dirname });
});
app.listen(3000, function () {
console.log('Listening on port 3000');
});
please follow the file path as :
I am successfully able to persist the data to my DB which has been entered from input text box(name, message) in index.html.
Happy coding !!

passport module on node.js - Reference Error: LocalStrategy is not defined

When I try to run my code it gives me Reference Error: LocalStrategy is not defined.
This is my first time using node.js and I hit a wall with this. I appreciate the help in advance.
I put all the code in one snippet so you can go through it easily. I have tried other posts for fixes but have been unsuccessful.
/***********
Modules
***********/
//Load the express library
var express = require('express');
//Create a new variable called “app”; we pass on the express() method.
var app = express();
//Set Port
var port = 7878;
var mongoose = require('mongoose'); //Place this on top; Loads mongoose library
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStratgy = require('passport-local').Strategy;
/*Body parser*///whenever you do a post request from the form, it gets the data through a URL encoded format.
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/js', express.static(__dirname + '/js'));
/*Initialize Passport*/
app.use(passport.initialize());
app.use(passport.session());
/***********
Database
***********/
/*Database connection - MongoDB*/
//Created from the command earlier. Ensure this is done on the first_db instance
var usr = 'admin';
var pwd = '123456';
var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';
var url = 'mongodb://' + usr + ':' + pwd + '#' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);
mongoose.connect(url, function(err) {
if(err) {
console.log('connection error: ', err);
} else {
console.log('connection successful');
}
});
/***********
Models
***********/
//User model
//Define our fields for the table
var UserSchema = new mongoose.Schema({
user_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
//Create model object
var User = mongoose.model('user', UserSchema);
/***********
Routes
***********/
var bcrypt = require('bcrypt-nodejs'); //should be placed on top
//Renders our html file
app.get('/', function (req, res, next) {
res.sendFile( __dirname + '/index.html');
});
//render register.html when /register is called
app.get('/register', function (req, res, next) {
res.sendFile( __dirname + '/register.html');
});
app.get('/home', function (req, res, next) {
res.sendFile(__dirname + '/home.html');
});
app.post('/login', passport.authenticate('local'),
function(req, res) {
res.redirect('/home');
});
/* Login logic for passport.authenticate*/
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if(user !== null) {
var isPasswordCorrect = bcrypt.compareSync(password, user.password);
if(isPasswordCorrect) {
console.log("Username and password correct!");
return done(null, user);
} else {
console.log("Password incorrect!");
return done(null, false);
}
} else {
console.log("Username does not exist!");
return done(null, false);
}
});
}
));
/**********
Serialize and Deserialize here for passport.authenticate
**********/
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(err, user);
});
app.post('/register', function (req, res, next) {
var password = bcrypt.hashSync(req.body.password);
req.body.password = password;
User.create(req.body, function(err, saved) {
if(err) {
console.log(err);
res.json({ message : err });
} else {
res.json({ message : "User successfully registered!"});
}
});
});
app.listen(port, '0.0.0.0', function() {
console.log('Server running at port ' + port);
});
The reason is you have defined var LocalStratgy, not LocalStrategy.
You're using it like this-
https://www.npmjs.com/package/passport-local-mongoose#configure-passportpassport-local
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
But I suggest you to use it like this -
https://www.npmjs.com/package/passport-local-mongoose#simplified-passportpassport-local-configuration
// CHANGE: USE "createStrategy" INSTEAD OF "authenticate"
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

Categories