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>
Related
I am trying to create a simple form handler using express. I tried the code below for my form:
<!DOCTYPE html>
<html lang="pt-br">
<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 href="./css/style.css" rel="stylesheet" type="text/css">
<script src="./js/register.js"></script>
<title>CAMPEONATO</title>
</head>
<body>
<div class="main-login">
<div class="left-login">
<h1>Cadastre-se<br>E participe do nosso campeonato</h1>
<img src="./img/soccer-animate.svg" class="left-login-image" alt="Futebol animado">
</div>
<form action="http://localhost:3000/register" method="POST">
<div class="right-login">
<div class="card-login">
<h1>Crie sua conta</h1>
<div class="textfield">
<label for="name">Nome Completo</label>
<input type="text" name="txtName" id="name" onchange="validateFields()" placeholder="Nome Completo">
</div>
<div class="textfield">
<label for="email">E-mail</label>
<input type="email" name="txtEmail" id="email" onchange="validateFields()" placeholder="E-mail">
</div>
<div class="textfield">
<label for="password">Senha</label>
<input type="password" name="txtPassword" id="password" onchange="validateFields()" placeholder="Senha">
</div>
<button class="btn-login" type="submit" id="login-button" disabled="true">CRIAR</button>
</div>
</div>
</form>
</div>
</body>
</html>
Here is my index.js:
// config inicial
const express = require('express')
const mongoose = require('mongoose')
const app = express()
const path = require('path')
const bodyParser = require('body-parser')
// forma de ler JSON / middlewares
app.use(
bodyParser.urlencoded({
extended: false,
}),
)
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'public')));
// rotas da API
const usersRoutes = require('./routes/usersRoutes')
app.use('/users', usersRoutes)
app.use('/register', usersRoutes)
And here is my routes/usersRoutes:
const router = require('express').Router()
const Users = require('../models/Users')
// CREATE - Criacao de Dados
router.post('/register', async (req, res) => {
// req.body
const{ name } = req.body.txtName;
const{ email } = req.body.txtEmail;
const{ password } = req.body.txtPassword;
const users = {
name,
email,
password
}
try {
await Users.create(users)
} catch (error) {
res.status(500).json({error:error})
}
})
module.exports = router
I keep getting the error "CANNOT POST /" after submitting the form. I've tried everything on the internet but the error remains, am I forgetting some module? Forgetting a route?
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 !
I'm doing a full stack web dev course. I follow along the instructor, but he was able to put bullet points upon HTML form input but I can't. There are some unnecessary code from previous lectures. But here is my code:
list.ejs
<!DOCTYPE html>
<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">
<title>To Do List</title>
</head>
<body>
<h1>
<%= kindOfDay %>
</h1>
<ul>
<li>Buy Ganja</li>
<li>Roll Ganja</li>
<li>Smoke Ganja</li>
<% for(var i=0;i<newListItems.lenth; i++){ %>
<li> <%= newListItems[i] %></li>
<% } %>
</ul>
<form action="/" method="post">
<input type="text" name="newItem">
<button type="submit" name="button">Add</button>
</form>
</body>
</html>
And here is my server file:
App.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
var items = [];
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function (req, res) {
var today = new Date();
var options = {
weekday: "long",
day: "numeric",
month: "long",
};
var day = today.toLocaleDateString("en-US", options);
res.render("list", { kindOfDay: day, newListItems: items });
});
app.post("/", function (req, res) {
var item = req.body.newitem;
items.push(item);
res.redirect("/");
});
app.listen(3000, function () {
console.log("Server Started at Port 3000");
});
Here is the screenshot. I cannot add extra points upon form submission!
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(express.urlencoded({extended:true}));
app.get("/",function(req,res){
var today = new Date();
var options = {
weekday: "long",
year:"numeric",
day: "numeric",
month:"long"
};
var day = today.toLocaleDateString("en-US",options);
res.render("index",{kindOfDay:day,tasks:tasks});
})
var tasks = [];
app.post("/",function(req,res){
const task = req.body.newItem;
tasks.push(task);
res.redirect("/");
})
app.listen(3000,function(){
console.log("Server is running");
})
<!-- index.ejs -->
<!DOCTYPE html>
<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">
<title>To-Do List App</title>
</head>
<body>
<h1><%= kindOfDay %> </h1>
<ul>
<li>Buy Food</li>
<li>Watch Movies</li>
<% for(var i=0;i<tasks.length;i++){ %>
<li><%= tasks[i] %> </li>
<% } %>
</ul>
<form action="/" method="POST">
<label for="newItem">Add New Task</label>
<input type="text" name="newItem" id="newItem">
<button type="submit">Add</button>
</form>
</body>
</html>
using the express-flash package together with passportjs, and I want to flash messages to a user.
App.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const sessions = require('express-session');
const passport = require('passport');
const passportInit = require('./config/passport');
const sessionStoreSQL = require('express-mysql-session')(sessions);
const logger = require('morgan');
const flash = require('express-flash');
const favicon = require('serve-favicon');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser('keyboard cat'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(sessions({
genid: (req) => {
return uuid.v1();
},
secret:'-----',
resave:false,
saveUninitialized:false,
store:sessionStore
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
passportInit(passport,userModel);
require('./routes/index')(app,passport);
require('./server/API/get')(app);
I use a custom middle ware function to map my errors to, so I can access all of them in my templates
app.get('*', function(req,res,next){
res.locals.successes = req.flash('success');
res.locals.errors = req.flash('error');
res.locals.warnings = req.flash('warning');
next();
});
Passport.js
passport.use('local-login', new localStategy({passReqToCallback:true},function (req,username,password,done){
const isValidPassword = (userpass,password) => {
return bcrypt.compareSync(password,userpass);
}
Model.findOne({
where:{
'username':username,
},
}).then(function(user){
if(!user) return done(null,false,req.flash('warning','User does not exist'));
if(!isValidPassword(user.password,password)) return done(null,false,req.flash('error','Incorrect password'));
return done(null, user);
}).catch(err => console.log(err));
}))
Here is where I flash messages to the user.
Then I have a EJS component that handles al my alerts
Alerts.ejs
<% if (errors.lenght > 0) { %>
<div class='header alert alert-danger alert-dismissible'>
<strong><i class="fa fa-exclamation-circle"></i> ERROR:</strong> <%- errors.message %>
<i class='fa fa-times'></i>
</div>
<% } %>
<% if (successes.lenght > 0 ) { %>
<div class='header alert alert-success alert-dismissible'>
<strong><i class="fa fa-check-circle"></i> Success!</strong> <%- successes.message %>
<i class='fa fa-times'></i>
</div>
<% } %>
<% if (warnings.lenght > 0) { %>
<div class='header alert alert-warning alert-dismissible'>
<strong><i class="fa fa-check-circle"></i> Warning:</strong> <%- warnings.message %>
<i class='fa fa-times'></i>
</div>
<% } %>
This is then included in my templates e.g login and register like so
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %> </title>
<% include components/header.ejs %>
</head>
<body>
<% include components/navbar.ejs %>
<div class="container-fluid">
<% include components/alerts.ejs %>
<div class="row justify-content-center">
<div class="col-auto">
<form method="POST" action="/login">
<div class="form-group">
<label for="login-username">Username</label>
<input name="username" type="text" class="form-control" id="loginUsername"
aria-describedby="emailHelp" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="login-password">Password</label>
<input name="password" type="password" class="form-control" id="loginPassword"
placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
<% include components/scripts.ejs %>
</html>
Routes.js
/* eslint-disable no-unused-vars */
module.exports = function (app,passport) {
app.get('/', async function (req, res) {
res.render('index', {title:'Home'});
});
app.post('/',function (req,res) {
})
app.get('/cryptofolio/:username',isAuthenticated, function(req,res) {
res.render('cryptofolio', {title:'Cryptofolio'});
})
app.post('/portfolio',function(req,res){
})
app.get('/login',function(req,res){
res.render('login',{title:'Login'});
});
app.post('/login',passport.authenticate('local-login',{successRedirect: '/',failureRedirect:'/login',failureFlash:true}));
app.get('/register',function (req,res){
res.render('register',{title:'Register'});
})
app.post('/register',passport.authenticate('local-register',{successRedirect: '/',failureRedirect:'/register',failureFlash:true}));
app.get('/logout',function (req,res) {
req.logout();
res.redirect('/');
})
function isAuthenticated(req,res,next){
if (req.isAuthenticated()){
return next();
}
res.redirect('/login');
}
};
But when I input wrong information no errors are being flashed like they should.D
i think the check inside the template is returning false, as it needs to be checking for length not lenght
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>