Getting undefined from req.body in express using body-parser - node.js

iv'e read and tried all solutions in all topics, i'm a begginer with 3 month of Experince in web devolepment. usually i program with python.
So i'm sorry for any begginer mistakes.
I'm trying to set up a register form.
I'm trying to send the register data to the console with console.log.
In other page of the website involving file upload i did it succsesfully using multer.
I dont know why , but when using body-parser im allways getting undifined . No matter what!
can you see any problems in the html or express.js code ?
(english is not my native language , sorry for any spelling mistakes.)
(the wierd charchter's are Hebrew)
HTML CODE ->
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<meta charset="utf-8">
<title>Register Page.</title>
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Heebo:wght#300&display=swap" rel="stylesheet">
<link rel="icon" href="favicon.ico?v=2">
</head>
<body>
<div class="register_div">
<h1 class="registerH1">טופס הרשמה למערכת</h1>
<img src="pngegg.png" alt="angle_photo" class="angleImg">
<form class="registerForm" action="/" method="post" >
<label for="Fname">שם פרטי:</label>
<br>
<input type="text" name="register_Fname" class="inputTextRegister" required id="register_Fname">
<br>
<label for="Lname">שם משפחה:</label>
<br>
<input type="text" name="register_Lname" class="inputTextRegister" required id="register_Lname">
<br>
<label for="email"> כתובת מייל: </label>
<br>
<input type="email" name="register_email" class="inputTextRegister" required id="register_email">
<br>
<label for="levelpass">סיסמת הדרגה:</label>
<br>
<input type="text" name="masonLevelpass" required id="masonLevelpass" class="inputTextRegister">
<br>
<label for="pass">סיסמה:</label>
<br>
<input type="password" name="register_password" value="********" class="inputTextRegister" required id="register_password">
הצג סיסמה:<input type="checkbox" onclick="showPassFunc()">
<br>
<br>
<button type="submit" name="submitbutton">הרשמה</button>
<div class="toRegister"><a class="second" href="login">התחברות</a></div>
</form>
</div>
<script>function showPassFunc() {
var x = document.getElementById("pass");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}</script>
</body>
</html>
epxress code ->
const express = require('express');
const request = require("request")
const ejs = require("ejs")
var path = require('path');
var favicon = require('serve-favicon');
const app = express();
const port = 8080;
const session = require('express-session');
var mysql = require('mysql');
const bodyParser = require('body-parser');
const https = require("https");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// connect to the database
require("dotenv").config()
const DB_HOST = process.env.DB_HOST
const DB_USER = process.env.DB_USER
const DB_PASSWORD = process.env.DB_PASSWORD
const DB_DATABASE = process.env.DB_DATABASE
const DB_PORT = process.env.DB_PORT
const db = mysql.createPool({
connectionLimit: 100,
host: DB_HOST,
user: DB_USER,
password: DB_PASSWORD,
database: DB_DATABASE,
port: DB_PORT
})
//CONNECT TO USERS TABLE FREEMASONS DATABASE
const bcrypt = require("bcrypt")
//CREATE USER
app.post('/', async(req, res, next) =>{
var fname = req.body.register_Fname;
var lname = req.body.register_Lname;
var email = req.body.register_email;
var levelpass = req.body.masonLevelpass;
var pass = req.body.register_password;
console.log(fname,lname,email,levelpass,pass)
})
//Static files
app.use(favicon(path.join(__dirname, '/public', 'favicon.ico')));
app.use(express.static('public'));
//EMD OF STATIC FILES
// Set views
app.set('views', './views')
app.set('view engine', 'ejs')
app.get('', (req, res) => {
res.render('index')
});
app.get('/upload_files', (req, res) => {
res.render('upload_files')
});
app.get('/my_account', (req, res) => {
res.render('my_account')
});
app.get('/login', (req, res) =>{
res.render('login')
});
app.get('/register', (req, res) =>{
res.render('register')
});
app.listen(port, function(){
console.log("server is started on port " + port);
});
// END OF VIEWS
Thank you !

Related

updating ejs variable with fetching APIs

I am trying to make this simple app where I would fetch some data from a free public API that would show the population of a specific state. However, I am having difficulty updating the population variable and I cannot figure out the problem. the app logs the population properly but fails to update it in the app it self.
/* Requiring NPM packages */
const express = require("express");
const ejs = require("ejs");
const fetch = require("node-fetch");
const bodyParser = require("body-parser");
const _ = require("lodash");
/* Using Express */
const app = express();
const port = 3000;
/* Using Static Files */
app.use(express.static(__dirname + "/public"));
/* Using ejs*/
app.set("view engine", "ejs");
/* Using Body-Parser */
app.use(bodyParser.urlencoded({ extended: true }));
/* Fetching API data */
let nation = "Not Chosen";
let year = "Not Chosen";
let myStatePopulation = "TBD";
const data = async (nation, year) => {
const response = await fetch(
"https://datausa.io/api/data?drilldowns=State&measures=Population&year=" +
year
);
const myJson = await response.json();
const allState = myJson.data;
let myState = allState.find((x) => x.State === nation);
myStatePopulation = myState.Population;
console.log(myStatePopulation);
};
// data();
/* Starting the server */
app.get("/", function (req, res) {
res.render("index", {
content: "United States Population",
state: nation,
year: year,
population: myStatePopulation,
});
});
/* Posting Data */
app.post("/", function (req, res) {
if (req.body.stateName && req.body.yearDate) {
nation = _.capitalize(req.body.stateName);
year = Number(req.body.yearDate);
data(nation, year);
res.redirect("/");
} else {
nation = "Not Chosen";
year = "Not Chosen";
myStatePopulation = "TBD";
console.log("redirecting to main page");
res.redirect("/");
}
});
app.listen(port, () => console.log("app is running on port : " + port));
just to make it more clear here is the content of the ejs file
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/css/styles.css" />
<title>US Population</title>
</head>
<body>
<div class="header centertext">
<h1><%= content %></h1>
</div>
<div class="content centertext">
<p>State : <%= state %></p>
<p>Year : <%= year %></p>
<p>Population : <%= population %></p>
</div>
<div class="form centertext">
<form action="/" method="post">
<div class="form inputs">
<input type="text" name="stateName" placeholder="type your state" />
</div>
<div class="form inputs">
<input
type="text"
name="yearDate"
placeholder="type your desired year (2013-2020)"
/>
</div>
<div class="form submit">
<button type="submit">Sumbit</button>
</div>
</form>
</div>
</body>
</html>

File Upload Using Multer and Mongodb

I am working on an Image Upload server using multer and mongodb following This GeeksForGeeks Post:
https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/
I did everything same as in this post but my localhost server is just loading and loading.
My Project Structure :
https://i.stack.imgur.com/p1NhC.png
App.js:
// Step 1 - set up express & mongoose
var express = require('express')
var app = express()
var bodyParser = require('body-parser');
var mongoose = require('mongoose')
var fs = require('fs');
var path = require('path');
require('dotenv/config');
// Step 2 - connect to the database
mongoose.connect(process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true }, err => {
console.log('connected')
});
// Step 3 - code was added to ./models.js
// Step 4 - set up EJS
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// Set EJS as templating engine
app.set("view engine", "ejs");
// Step 5 - set up multer for storing uploaded files
var multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({ storage: storage });
// Step 6 - load the mongoose model for Image
var imgModel = require('./model');
// Step 7 - the GET request handler that provides the HTML UI
app.get('/', (req, res) => {
imgModel.find({}, (err, items) => {
if (err) {
console.log(err);
res.status(500).send('An error occurred', err);
}
else {
res.render('imagesPage', { items: items });
}
});
});
// Step 8 - the POST handler for processing the uploaded file
app.post('/', upload.single('image'), (req, res, next) => {
var obj = {
name: req.body.name,
desc: req.body.desc,
img: {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
contentType: 'image/png'
}
}
imgModel.create(obj, (err, item) => {
if (err) {
console.log(err);
}
else {
// item.save();
res.redirect('/');
}
});
});
// Step 9 - configure the server's port
var port = process.env.PORT || '3000'
app.listen(port, err => {
if (err)
throw err
console.log('Server listening on port', port)
})
Model.js:
// Step 3 - this is the code for ./models.js
var mongoose = require('mongoose');
var imageSchema = new mongoose.Schema({
name: String,
desc: String,
img:
{
data: Buffer,
contentType: String
}
});
//Image is a model which has a schema imageSchema
module.exports = new mongoose.model('Image', imageSchema);
.env:
MONGO_URL = mongodb://localhost/mongo
PORT = 5500
imagesPage.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Uploading</title>
</head>
<body>
<h1>To Upload Image on mongoDB</h1>
<hr>
<div>
<form action="/" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Image Title</label>
<input type="text" id="name" placeholder="Name"
value="" name="name" required>
</div>
<div>
<label for="desc">Image Description</label>
<textarea id="desc" name="desc" value="" rows="2"
placeholder="Description" required>
</textarea>
</div>
<div>
<label for="image">Upload Image</label>
<input type="file" id="image"
name="image" value="" required>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
<hr>
<h1>Uploaded Images</h1>
<div>
<% items.forEach(function(image) { %>
<div>
<div>
<img src="data:image/<%=image.img.contentType%>;base64,
<%=image.img.data.toString('base64')%>">
<div>
<h5><%= image.name %></h5>
<p><%= image.desc %></p>
</div>
</div>
</div>
<% }) %>
</div>
</body>
</html>
Please tell what i am doing wrong.
I very new to backend so I don't know what to do
Thanks

How do I combine two GET requests/databases into 1?

I want to combine a weather API with a form where you fill in your mood into 1 app:
a form where you fill in you city (so you get the weather) and where you fill in your mood of that day.
In my server.js file I have two GET and two POST functions.
However, I think I can only use res.render('index',...) once.
How to combine the two GET functions into 1 working function?
server.js file
const express = require('express')
const app = express()
app.use(express.static('./public'))
// --> npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// --> npm install ejs
app.set('view engine', 'ejs');
// --> npm install request
// --> npm install request-promise
const request = require('request-promise');
// --> npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://MONGO_HOST/test?retryWrites=true&w=majority');
// apiKey
const apiKey = 'XXX';
// database weather
var citySchema = new mongoose.Schema({
city: String
});
var cityModel = mongoose.model('City', citySchema);
// database mood
var moodSchema = new mongoose.Schema({
name: String,
description: String,
date: String
});
var moodModel = mongoose.model('Mood', moodSchema);
// function which gets a list of moods in the database
async function getDiary(moods) {
var diary_data = [];
for (var mood_obj of moods) {
var name = mood_obj.name;
var description = mood_obj.description;
var date = mood_obj.date;
var diary = {
name : name, // variable declared above
description : description, // variable declared above
date : date // variable declared above
};
diary_data.push(diary);
}
return diary_data;
};
// GET route mood
app.get('/', function (req, res) {
moodModel.find({}, function(err, moods){
console.log(moods);
getDiary(moods).then(function(results){
var diary_data = {diary_data: results};
res.render('index', diary_data);
})
});
})
// function which gets a list of cities in the database
async function getWeather(cities) {
var weather_data = [];
for (var city_obj of cities) {
var city = city_obj.name;
var url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apiKey}`;
var response_body = await request(url);
var weather_json = JSON.parse(response_body);
var weather = {
city : city, // variable declared in this document
temperature: weather_json.main.temp, // variable from API data
description : weather_json.weather[0].description, // variable from API data
icon : weather_json.weather[0].icon, // variable from API data
};
weather_data.push(weather);
}
return weather_data;
};
// GET route weather
app.get('/', function (req, res) {
cityModel.find({}, function(err, cities){
console.log(cities);
getWeather(cities).then(function(results){
var weather_data = {weather_data: results};
res.render('index', weather_data);
})
});
})
// POST route mood
app.post('/', function(req, res) {
var newMood = new moodModel({
name: req.body.mood_name,
description: req.body.mood_description,
date: req.body.mood_date
});
newMood.save();
res.redirect('/');
})
// POST route weather
app.post('/', function(req, res) {
var newCity = new cityModel({city: req.body.city_name});
newCity.save();
res.redirect('/');
});
// setup port
const port = 3000;
app.listen(port, function() {
console.log(`server is listening on port ${port}`);
})
index.ejs file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<% for (diary of diary_data) { %>
<div class="moodBox">
<span class="title"><%= diary.name %></span>
<br>
<span class="title"><%= diary.description %></span>
<br>
</div>
<% } %>
<% for (weather of weather_data) { %>
<div class="weatherBox">
<span class="title"><%= weather.city %></span>
<br>
<span class="subtitle"><%= weather.temperature %></span>
<br> <%= weather.description %>
</div>
<% } %>
<fieldset>
<form method="post" action="/">
<div>
<label for="mood_name">mood name</label>
<input type="text" name="mood_name" required>
</div>
<div>
<label for="mood_description">mood description</label>
<input type="text" name="mood_description" required>
</div>
<div>
<input type="date" name="mood_date">
<div id="theDate"></div>
</div>
<div>
<label for="city_name">City name</label>
<input type="text" name="city_name">
</div>
<button type="submit">Submit</button>
</form>
</fieldset>
</div>
<script src="/extra.js"></script>
</body>
</html>

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

Chat app. using express and socket.io

I have a group chat app. When client login with his email and password, he would be directed to chat page with his name on top and he would able to chat with online user.How can my app. identify from which user message was sent. One possibility is to send socket.id along with message to server for identifying user but socket.id get changed on refreshing the page.
login.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/loginstyle.css" />
</head>
<body>
<form class="css" method="post" action="http://192.168.1.3:9373/valid" >
<fieldset >
<input type="text" name="email" class="inputemail" placeholder="Email" />
</fieldset>
<fieldset >
<input type="password" name="pass" class="inputpassword" placeholder="Password" />
</fieldset >
<fieldset >
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://192.168.1.3:9373');
</script>
</body>
</html>
chat.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="name"> Welcome </div>
<br></br>
<div class="chat"></div>
<form>
<input type="text" class="msg"> </input>
<button type="submit" class="enter">Send</button>
<input type="file" class="file"></input>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://192.168.1.3:9373');
var online=[];
var checkFile=0;
$.get("/getName", function(string){
username=string;
$('.name').append(username);
});
$('.enter').bind("click",function(){
$.get("/getMsg", function(){
setTimeout (function(){
socket.emit('chat message',$('.msg').val() );
$('.msg').val('');
},0);
});
return false;
});
socket.on('chatmessage', function(name,msg){
var block= $("<div class='message'> </div>");
if(msg.length){
var messenger= $("<div class='messenger'> </div>");
messenger.append(name);
block.append(messenger);
var text;
text=$("<div class='text'></div>");
text.append(msg);
block.append(text);
block.append($("<div class='pad'></div>"));
$('.chat').append(block);
}
});
});
</script>
</body>
</html>
server.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server)
, os = require('os')
, open = require('open')
, bodyParser = require('body-parser')
, connect = require('connect')
, cookieParser = require('cookie-parser')
, session = require('express-session')
, sessionStore = session.MemoryStore()
, async = require('async')
, mysql = require("mysql");
var id=[];
var a;
server.listen(9373,'192.168.1.3');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser("secret"));
app.use(session({
store: sessionStore,
secret: "54321",
saveUninitialized: true,
resave: true
}));
app.get('/loginme', function (req, res) {
res.sendfile(__dirname + '/loginmysql.html');
});
app.get('/option', function (req, res) {
res.sendfile(__dirname + '/option.html');
});
app.get('/getName', function (req, res) {
var r = {};
r.name = req.session.userid;
res.send(r.name);
});
app.get('/getMsg', function (req, res) {
a = req.session.id;
res.json(a);
});
app.get('/chat', function (req, res) {
res.sendfile(__dirname + '/chat.html');
});
app.post('/valid', function (req, res) {
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "vk123",
"database": "login"
});
connection.connect();
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
var name=rows[0].name;
req.session.userid = name;
id.push({sid:req.session.id, username:req.session.userid});
res.redirect('http://192.168.1.3:9373/option');
io.sockets.on('connection', function (socket){
io.emit('name',name);
});
}
});
connection.end();
});
io.sockets.on('connection', function (socket){
socket.on('chat message', function(msg){
var user;
var i;
for(i=id.length-1; i>=0; i--){
if(id[i].sid == a){
user=id[i].username;
break;
}
}
io.emit('chatmessage',id[i].username,msg);
});
});
app.use(express.static(__dirname+'/public'));

Resources