How do I combine two GET requests/databases into 1? - node.js

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>

Related

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

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 !

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 to use sweetalert in nodejs?

I have a nodejs code given with html code, I want to show a sweet alert on client side,after process a function in nodejs?.
var express = require('express');
var router = express.Router();
const Swal = require('sweetalert2');
router.post('/add', function(req, res, next) {
Swal('Hello world!');
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form action="/add" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
Here's the only way you can show a popup swal
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.json("Hello world!")
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form id="form" action="#" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
<script>
//import JQuery from script
//import swal script
$("#form").on("submit", function(e){
e.preventDefault();
$.ajax({
url: "/add",
method: "post"
}).done(d=>{
swal(e.responseJSON);
});
})
</script>
Here you can do using EJS
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.status(201).render('new', { isAdded : true } );
});
In HTML side
<% if (isAdded) { %>
<script>
Swal.fire(
'Good job!',
'Data saved',
'success'
)
</script>
<% } %>
In order to deal with this, you can use query parameters.
So, Here is what you can do
On the server
var express = require('express');
var router = express.Router();
router.post('/login', (req, res)=>{
res.redirect("/login?success=true&message=Logged In Successfully")
});
On the Client-Side (EJS)
<script>
var urlParams = new URLSearchParams(window.location.search);
if(urlParams.has('success') && urlParams.get('success')){
swal({
title: "Failed",
text: `${message}`,
icon: "error",
button: "Okay",
}).then(()=>{
console.log(window.location.hostname)
window.location.replace(window.location.origin + '/login');
})
}
This will simply popup swal. And you can toggle the value of success to render error and success messages.

Cannot Post in Node.js Express

Following code is giving me the error
Cannot POST /campgrounds/5b0d6eb8a0f5990b452e8212/comments
When I submit my form from new.js i get an error.
I have one more Post Route and it works fine which means that my body-parser has no issue.
The aim here is when the user submit the comment, he should be navigated back to show.ejs where the camps are shown as well as the new comment
I am running this app on Cloud9.
App.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Campground = require("./models/campground");
var Comment = require("./models/comment");
var seedDB = require("./seeds.js");
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded(
{
limit: "10mb",
extended:true
}));
app.set("view engine", "ejs");
seedDB();
app.get("/",function(req,res){
res.render("landing");
});
app.get("/campgrounds",function(req,res){
// Get all Campround from db
Campground.find({},function(err,allCampgrounds){
if(err){
console.log(err);
} else{
res.render("campgrounds/index",{campgrounds:allCampgrounds});
}
});
//
});
app.post("/campgrounds", function(req,res){
//res.send("Hitting the Post ROute");
var name = req.body.name;
var image = req.body.image;
var description = req.body.description;
var newCampground = {name: name, image: image,description : description};
// New Campground and Save to DB..
Campground.create(newCampground,function(err,newlyCreated){
if(err){
console.log(err);
} else{
res.redirect("/campgrounds");
}
});
// campgrounds.push(newCampground);
//get data from form and add them to array...
});
app.get("/campgrounds/new",function(req, res) {
res.render("campgrounds/new");
});
//Show More Info on Camps
app.get("/campgrounds/:id",function(req, res) {
// Find Campground using Id
Campground.findById(req.params.id).populate("comments").exec(function(err,foundCamp){
if(err){
console.log(err);
}else{
//render show page
console.log(foundCamp);
res.render("campgrounds/show",{campground:foundCamp});
}
});
// req.params.id
});
/*
====================
Comments
+===================*/
app.get("/campgrounds/:id/comments/new", function(req, res) {
Campground.findById(req.params.id,function(err,campground){
if(err){
console.log(err);
}else{
res.render("comments/new", {campground:campground});
}
});
});
app.post("campgrounds/:id/comments",function(req,res){
//luk for campground
Campground.findById(req.params.id, function(err,campground){
if(err){
console.log(err);
res.redirect("/campgrounds");
} else {
Comment.create(req.body.comment, function(err, comment){
if(err){
console.log(err);
}else{
// var text = req.body.text;
// var author = req.body.text;
// console.log(text);
campground.comments.push(comment);
campground.save();
//console.log(comment);
res.redirect('/campgrounds/' + campground._id);
}
});
}
});
//create new cpmment
//comment new comment to
//redirect
});
app.listen(process.env.PORT,process.env.IP, function(){
console.log("Yelp Server Started...")
});
New.js
<% include ../partials/header %>
<div class="container">
<h1 style="text-align:center;">Add New Comment to <%= campground.name %></h1>
<div class="row">
<div style="width:30%;margin:0 auto;">
<form action="/campgrounds/<%= campground._id %>/comments" method="POST">
<div class="form-group">
<input class="form-control" type="text" name="comment[text]" placeholder="Text">
</div>
<div class="form-group">
<input class="form-control" type="text" name="comment[author]" placeholder="Author">
</div>
<button class="btn btn-lg btn-primary btn-block">Submit</button>
</form>
</div>
</div>
</div>
<% include ../partials/footer %>
Show.ejs
<% include ../partials/header %>
<h1><%= campground.name %></h1>
<p></p>
<img src="<%= campground.image %>"/>
<p><%= campground.description %></p>
<p>
<a class="btn btn-success" href="/campgrounds/<%= campground._id %>/comments/new">Comment</a>
</p>
<% campground.comments.forEach(function(comment){ %>
<p><strong><%= comment.author %></strong> - <%= comment.text %> </p>
<% }); %>
<% include ../partials/footer %>
Please add a forward-slash character to the start of your route path parameter.
Currently you have "campgrounds/:id/comments"
You are expecting a POST request on "/campgrounds/:id/comments"

Resources