How can I send my non-input ejs to MongoDB Atlas - node.js

Here is my app.js
const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://Tibor:asdfsadf#weatherdb.pcmad.mongodb.net/weatherDB")
//Adatszerkezet (schema) Mongo-hoz
const weatherSchema = {
varos: String,
lat: Number,
lon: Number,
homerseklet: Number,
meresideje: Date,
szelirany: Number,
szelsebesseg: Number,
legnyomashPa: Number,
legnyomashgmm: Number,
paratartalom: Number,
felhozet: Number
}
//model
const Weather = mongoose.model("Weather", weatherSchema)
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get('/', (req, res) => {
//res.send('express működik')
res.render('index', {data: ''});
})
//API elérése(éss mongoDB Post)
app.post('/', (req, res) => {
const location = req.body.location ? req.body.location : "Budapest";
const appId = "asdfasdfasd";
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=" + appId + "&units=metric";
https.get(url, (response) => {
if (response.statusCode === 200) {
response.on("data", (data) => {
const weatherData = JSON.parse(data);
res.render('index', {data: weatherData});
})
} else {
res.render('index', {data: "0"});
}
});
let newWeather = new Weather({
varos: req.body.varos,
lat: req.body.lat,
lon: req.body.lon,
homerseklet: req.body.homerseklet,
meresideje: req.body.homerseklet,
szelirany: req.body.szelirany,
szelsebesseg: req.body.szelsebesseg,
legnyomashPa: req.body.legnyomashPa,
legnyomashgmm: req.body.legnyomashgmm,
paratartalom: req.body.paratartalom,
felhozet: req.body.felhozet
})
newWeather.save();
});
app.listen(process.env.PORT || 3000, function(){
console.log('A szerver fut/Port:3000');
});
And here is my index.ejs.
<!DOCTYPE html>
<html lang="hu">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WeatherApp</title>
<link rel="stylesheet" href="/public/style.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<!-- Már régóta ki akartam próbálni az EJS-t és úgy gondoltam ez egy jó alkalom rá. -->
<!-- Ha talált adatot -->
<% if (data === '') { %>
<div class="container mt-4 col-lg-5">
<!-- Title -->
<h4 class="font-weight-bold">Melyik város időjárását szeretnéd megtekinteni?</h4>
<!-- Város gombok -->
<form action="/" method="post">
<div class="form-group mt-3">
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Budapest">Budapest</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Győr">Győr</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Debrecen">Debrecen</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Miskolc">Miskolc</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Pécs">Pécs</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Sopron">Sopron</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Szeged">Szeged</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Gyékényes">Gyékényes</button>
</div>
</form>
<% } else { %>
<div class="container mt-3 ">
<!-- Időjárás szerkezet -->
<div class="card">
<div class="card-body">
<!-- "head" -->
<h5 class="card-title" name="varos"><%= data.name %></h5>
<h8><%= data.sys.country %></h8>
<div class="container">
<p class="text-muted" name="lat"><%= data.coord.lat %></p>
<p class="text-muted" name="lon"><%= data.coord.lon %></p>
</div>
<!-- icon -->
<img class="float-right" src="http://openweathermap.org/img/wn/<%= data.weather[0].icon %>#2x.png" alt="icon">
<!-- Hőmérséklet -->
<p class="display-1" name="homerseklet"><%= data.main.temp%><sup>o</sup>C</p>
<!-- Hőérzet -->
<span class="text-muted">Hőérzet: <%= data.main.feels_like %><sup>o</sup>C</span>
<!-- Az adatok mérésének időpontja -->
<h5 class="font-weight-bold">Mérés időpontja:</h5>
<h6 name="meresideje"><%= new Date(data.dt*1000) %></h6>
<!-- Másodlagos adatok -->
<div class="container mt-3 text-center ">
<div class="row font-weight-bold border-top border-info">
<div class="col border-right border-info"><i class="fas fa-paper-plane"></i> Szélirány</div>
<div class="col"></div>
<div name="szelirany" class="col"><%= data.wind.deg %>°</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-wind"></i> Szélsebesség</div>
<div class="col"></div>
<div name="szelsebesseg" class="col"><%= data.wind.speed %>m/s</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-spinner"></i> Légnyomás</div>
<div name="legnyomashPa" class="col"><%= data.main.pressure %>(hPa)</div>
<div name="legnyomashgmm" class="col"><%= data.main.pressure * 0.75 %>(hgmm)</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-water"></i> Páratartalom</div>
<div class="col"></div>
<div name="paratartalom" class="col"><%= data.main.humidity %>%</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-eye"></i> Látási-viszonyok</div>
<div class="col"></div>
<div class="col"><%= data.visibility/1000 %>km</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-cloud"></i> Felhőzet</div>
<div class="col"></div>
<div name="felhozet" class="col"><%= data.clouds.all %>%</div>
</div>
</div>
</div>
</div>
<!-- Másik város gomb(to /) -->
<div class="text-center">
Másik Település
</div>
</div>
<!-- ejs end -->
<% } %>
<script src="https://kit.fontawesome.com/ad862d8e11.js" crossorigin="anonymous">
</script>
</body>
</html>
So this is it.
Somewhy if I check MongoDB I only see empty objects with only an id, maybe I didn't submit it or my ejs is wrong? (I'm new to this)
Also if anyone knows how I can do something like, checking if since the previous date 10 minutes didn't pass then use those measurements?
Any help is welcome!

mongoose.connect('mongodb://localhost:27017/test');
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));```
```.save()``` is returns a promise resolves with ```(err)```
check that

Related

getting error "Cannot read property 'username' of undefined" from my ejs file

I am developing an E-Commerce website using MERN stack. I want to display two different navbars based on the condition if the user is logged-in or not! and I have used res.locals in my app.js file to expose data to all templates but when I am using this data in my index.ejs file by user.username, its showing me above error.
I am stuck in this problem and have searched for this whole day but can't get any solution.
Here is my app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var mongoose = require('mongoose');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(session({
name: 'uid',
secret: 'LoginSession',
saveUninitialized: false,
resave: false,
cookie: {
expires: 6000000
}
}))
app.use(function(req,res,next){
res.locals.user = req.session.user;
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static('public'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Here is my index.ejs file
<!DOCTYPE html>
<html lang="en">
<head>
<% include partials/head %>
</head>
<body>
<% if (!user.username) { %>
<% include partials/navhome %>
<%} else { %>
<% include partials/navhome1 %>
<% } %>
<div class="main-banner header-text" id="top">
<div class="Modern-Slider">
<!-- Item -->
<div class="item item-1" style="background-image: url(../images/slider-image-1-1920x900.jpg);">
<div class="img-fill">
<div class="text-content">
<h6>New Arrival!</h6>
<h4>Iphone 12 Pro</h4>
Shop Now
</div>
</div>
</div>
<!-- // Item -->
<!-- Item -->
<div class="item item-2" style="background-image: url(../images/slider-image-2-1920x900.jpg);">
<div class="img-fill">
<div class="text-content">
<h6>New Arrival!</h6>
<h4>Samsung S21 Ultra 5G</h4>
Shop Now
</div>
</div>
</div>
<!-- // Item -->
<!-- Item -->
<div class="item item-3" style="background-image: url(../images/slider-image-3-1920x900.jpg);">
<div class="img-fill">
<div class="text-content">
<h6>New Arrival!</h6>
<h4>Oneplus 9 pro 5G</h4>
Shop Now
</div>
</div>
</div>
<!-- // Item -->
</div>
</div>
<!-- Banner Ends Here -->
<div class="services">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-heading">
<h2>Featured <em>Smart-Phones</em></h2>
<span>Phones with best prices and specifications</span>
</div>
</div>
<div class="col-md-4">
<div class="service-item">
<img src="./images/product-1-720x480.jpg" alt="">
<div class="down-content">
<h4>Apple Iphone 7</h4>
<div style="margin-bottom:10px;">
<span>Rs </sup>35000.00 </span>
</div>
<p>The Iphone 7 attributes 4.7 inch screen, 12 MP back and 7 MP front camera. It comes with iOS 10.0.1 which is upgradable to iOS 11.2.5 and runs on 2.34GHz processor.</p>
Shop Now
</div>
</div>
<br>
</div>
<div class="col-md-4">
<div class="service-item">
<img src="./images/product-2-720x480.jpg" alt="">
<div class="down-content">
<h4>Realme 5 pro</h4>
<div style="margin-bottom:10px;">
<span>Rs </sup>32000.00 </span>
</div>
<p>The new Realme 5 Pro is packed with a powerful chipset and high-quality camera setup. The handset is powered by Snapdragon 712 chipset.</p>
Shop Now
</div>
</div>
<br>
</div>
<div class="col-md-4">
<div class="service-item">
<img src="./images/product-3-720x480.jpg" alt="">
<div class="down-content">
<h4>Apple Iphone 11 pro</h4>
<div style="margin-bottom:10px;">
<span>Rs </sup>254,600.00 </span>
</div>
<p>Apple iPhone 11 Pro Max is packed with high-end specs and will be the flagship of the series. The phone is powered by A13 chip.</p>
Shop Now
</div>
</div>
<br>
</div>
<div class="col-md-4">
<div class="service-item">
<img src="./images/OnePlus-Nord.jpg" alt="">
<div class="down-content">
<h4>One Plus Nord</h4>
<div style="margin-bottom:10px;">
<span>Rs </sup>54,500.00 </span>
</div>
<p>This device will be powered by one of the latest chipsets available for smartphones in the market that is called Qualcomm SM6350 Snapdragon 690 5G.</p>
Shop Now
</div>
</div>
<br>
</div>
<div class="col-md-4">
<div class="service-item">
<img src="./images/SamsungGalaxyS20Ultra__1_.jpg" alt="">
<div class="down-content">
<h4>Samsung Galaxy S20</h4>
<div style="margin-bottom:10px;">
<span>Rs </sup>170,999.00 </span>
</div>
<p>Samsung Galaxy S20's chipset is paired with 8 gigabytes of RAM. The high-end RAM and chipset will the processing speed of the smartphone very fast.</p>
Shop Now
</div>
</div>
<br>
</div>
<div class="col-md-4">
<div class="service-item">
<img src="./images/huawei-p40-black.jpg" alt="">
<div class="down-content">
<h4>Huawei P40 Pro</h4>
<div style="margin-bottom:10px;">
<span>Rs </sup>179,999.00 </span>
</div>
<p>P40 pro has 8 GB of RAM and Krin 990 powerfull processor. It supports wireless charging and equipped with 5500mAh battery capacity.</p>
Shop Now
</div>
</div>
<br>
</div>
</div>
</div>
</div>
<div class="fun-facts">
<div class="container">
<div class="more-info-content">
<div class="row">
<div class="col-md-6">
<div class="left-image">
<img src="./images/about-1-570x350.jpg" class="img-fluid" alt="">
</div>
</div>
<div class="col-md-6 align-self-center">
<div class="right-content">
<h2>Get to know about <em>our shop</em></h2>
<p>Our shop is recognised as the world no 1 selling smart phone shop because we provides best deals and original products!</p>
Read More
</div>
</div>
</div>
</div>
</div>
</div>
<div class="testimonials">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-heading">
<h2>What they say <em>about us</em></h2>
<span>feedback from our greatest customers</span>
</div>
</div>
<div class="col-md-12">
<div class="owl-testimonials owl-carousel">
<div class="testimonial-item">
<div class="inner-content">
<h4>George Walker</h4>
<span>Chief Financial Analyst</span>
<p>"Phone E-Shop provided us with the best smart phones in the market under best pricing"</p>
</div>
</div>
<div class="testimonial-item">
<div class="inner-content">
<h4>John Smith</h4>
<span>Market Specialist</span>
<p>"Phone E-Shop is the best store right now in smart phone industry which cares about the customer opinoin"</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer Starts Here -->
<footer>
<div class="container">
<div class="row">
<div class="col-md-3 footer-item">
<h4>Phone E-Shop</h4>
<p>The store which have all smart phones that you are looking for!</p>
<ul class="social-icons">
<li><a rel="nofollow" href="https://www.facebook.com" target="_blank"><i class="fa fa-facebook"></i></a></li>
<li><i class="fa fa-twitter"></i></li>
<li><i class="fa fa-linkedin"></i></li>
</ul>
</div>
<div class="col-md-3 footer-item">
<h4>Additional Pages</h4>
<ul class="menu-list">
<li>Go to top</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
</div>
<div class="col-md-3 footer-item last-item">
<h4>Contact Us</h4>
<div class="contact-form">
<form id="contact footer-contact" action="" method="post">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<fieldset>
<input name="name" type="text" class="form-control" id="name" placeholder="Full Name" required="">
</fieldset>
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<fieldset>
<input name="email" type="text" class="form-control" id="email" pattern="[^ #]*#[^ #]*" placeholder="E-Mail Address" required="">
</fieldset>
</div>
<div class="col-lg-12">
<fieldset>
<textarea name="message" rows="6" class="form-control" id="message" placeholder="Your Message" required=""></textarea>
</fieldset>
</div>
<div class="col-lg-12">
<fieldset>
<button type="submit" id="form-submit" class="filled-button">Send Message</button>
</fieldset>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</footer>
<div class="sub-footer">
<div class="container">
<div class="row">
<div class="col-md-12">
<p>
Copyright © 2021 Phone E-Shop - All right reserved.
</p>
</div>
</div>
</div>
</div>
<% include partials/script %>
</body>
</html>
Let me know if anyone of you want any other file!
Thank you in advance!

Vue not opens .json file with axios hook

Making my first steps in vue. I am crashing in importing a .json file. This job concernes a small shop. Goal of this paragraph is to enter 4 products in the shop. The productfiles are imported with an Axios hook. But the Vue Dev Tool errors an undefined (see picture). When loading the website the div with v-else is automatically loaded.
The products.json files is nested in the same folder as index.html. http://localhost:8000/products.json shows me the .json file.
Here you 'll find all the code for this small shop. Even with a copy/paste of this code mine is not working. I also made it smaller with the relevant code:
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Pet Depot</title>
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/app.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div id="app">
<header>
<div class="navbar navbar-default">
<div class="navbar-header">
<h1>{{ sitename }}</h1>
</div>
<div class="nav navbar-nav navbar-right cart">
<button type="button" class="btn btn-default btn-lg" v-on:click="showCheckout">
<span class="glyphicon glyphicon-shopping-cart">{{ cartItemCount}}</span> Checkout
</button>
</div>
</div>
</header>
<main>
<div v-if="showProduct"> <!--not working-->
<div v-for="product in sortedProducts">
<div class="row">
<div class="col-md-5 col-md-offset-0">
<figure>
<img class="product" v-bind:src="product.image">
</figure>
</div>
<div class="col-md-6 col-md-offset-0 description">
<h1 v-text="product.title"></h1>
<p v-html="product.description"></p>
<p class="price">
{{product.price | formatPrice}}
</p>
<button class=" btn btn-primary btn-lg" v-on:click="addToCart(product)" v-if="canAddToCart(product)">Add to cart</button>
<button disabled="true" class=" btn btn-primary btn-lg" v-else>Add to cart</button>
<span class="inventory-message" v-if="product.availableInventory - cartCount(product.id) === 0">
All Out!
</span>
<span class="inventory-message" v-else-if="product.availableInventory - cartCount(product.id) < 5">
Only {{product.availableInventory - cartCount(product.id)}} left!
</span>
<span class="inventory-message" v-else>
Buy Now!
</span>
<div class="rating">
<span v-bind:class="{'rating-active' :checkRating(n, product)}" v-for="n in 5">
☆
</span>
</div>
</div>
<!-- end of col-md-6-->
</div>
<!-- end of row-->
<hr />
</div>
<!-- end of v-for-->
</div>
<!-- end of showProduct-->
<div v-else>
<!--skipped this part-->
</div>
</main>
</div>
<!-- end of app-->
</div>
<script type="text/javascript">
var APP_LOG_LIFECYCLE_EVENTS = true;
var webstore = new Vue({
el: '#app',
data: {
sitename: "Vue.js Pet Depot",
showProduct: true,
a: false,
states: []
},
order: []
},
products: [],
cart: []
},
methods: {
checkRating(n, myProduct) {
return myProduct.rating - n >= 0;
},
addToCart(aProduct) {
this.cart.push(aProduct.id);
},
showCheckout() {
this.showProduct = this.showProduct ? false : true;
},
submitForm() {
alert('Submitted');
},
canAddToCart(aProduct) {
//return this.product.availableInventory > this.cartItemCount;
return aProduct.availableInventory > this.cartCount(aProduct.id);
},
cartCount(id) {
let count = 0;
for (var i = 0; i < this.cart.length; i++) {
if (this.cart[i] === id) {
count++;
}
}
return count;
}
},
computed: {
cartItemCount() {
return this.cart.length || '';
},
sortedProducts() {
if (this.products.length > 0) {
let productsArray = this.products.slice(0);
console.log(productsArray);
console.log(this.products);
function compare(a, b) {
if (a.title.toLowerCase() < b.title.toLowerCase())
return -1;
if (a.title.toLowerCase() > b.title.toLowerCase())
return 1;
return 0;
}
return productsArray.sort(compare);
}
}
},
filters: {
formatPrice(price) { //#B
..
}
},
beforeCreate: function () { //#B
if (APP_LOG_LIFECYCLE_EVENTS) { //#B
..
},
created: function () {
axios.get('./products.json')
.then((response) => {
this.products = response.data.products;
console.log(this.products);
});
},
beforeMount: function () {
..
},
mounted: function () {
..
},
beforeUpdate: function () {
..
},
updated: function () {
..
},
beforeDestroyed: function () {
..
},
destroyed: function () {
..
}
});
</script>
</body>
</html>
I tried out the same code here and it's working fine, i had did axios call to this json file :
https://raw.githubusercontent.com/ErikCH/VuejsInActionCode/master/chapter-05/products.json
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Pet Depot</title>
<script src="https://unpkg.com/vue"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/app.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div id="app">
<header>
<div class="navbar navbar-default">
<div class="navbar-header">
<h1>{{ sitename }}</h1>
</div>
<div class="nav navbar-nav navbar-right cart">
<button type="button" class="btn btn-default btn-lg" v-on:click="showCheckout">
<span class="glyphicon glyphicon-shopping-cart">{{ cartItemCount}}</span> Checkout
</button>
</div>
</div>
</header>
<main>
<div v-if="showProduct">
<div v-for="product in sortedProducts">
<div class="row">
<div class="col-md-5 col-md-offset-0">
<figure>
<img class="product" v-bind:src="product.image">
</figure>
</div>
<div class="col-md-6 col-md-offset-0 description">
<h1 v-text="product.title"></h1>
<p v-html="product.description"></p>
<p class="price">
{{product.price | formatPrice}}
</p>
<button class=" btn btn-primary btn-lg" v-on:click="addToCart(product)" v-if="canAddToCart(product)">Add to cart</button>
<button disabled="true" class=" btn btn-primary btn-lg" v-else>Add to cart</button>
<span class="inventory-message" v-if="product.availableInventory - cartCount(product.id) === 0">All Out!
</span>
<span class="inventory-message" v-else-if="product.availableInventory - cartCount(product.id) < 5">
Only {{product.availableInventory - cartCount(product.id)}} left!
</span>
<span class="inventory-message" v-else>Buy Now!
</span>
<div class="rating">
<span v-bind:class="{'rating-active' :checkRating(n, product)}" v-for="n in 5">☆
</span>
</div>
</div>
<!-- end of col-md-6-->
</div>
<!-- end of row-->
<hr />
</div>
<!-- end of v-for-->
</div>
<!-- end of showProduct-->
<div v-else>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-info">
<div class="panel-heading">Pet Depot Checkout</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-12">
<h4>
<strong>Enter Your Information</strong>
</h4>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<strong>First Name:</strong>
<input v-model.trim="order.firstName" class="form-control" />
</div>
<div class="col-md-6">
<strong>Last Name:</strong>
<input v-model.trim="order.lastName" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<strong>Address:</strong>
</div>
<div class="col-md-12">
<input v-model.trim="order.address" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<strong>City:</strong>
</div>
<div class="col-md-12">
<input v-model.trim="order.city" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<strong>State:</strong>
<select v-model="order.state" class="form-control">
<option disabled value="">State</option>
<option v-for="(state, key) in states" v-bind:value="state">
{{key}}
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<strong>Zip / Postal Code:</strong>
<input v-model.number="order.zip" class="form-control" type="number" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 boxes">
<input type="checkbox" id="gift" value="true" v-bind:true-value="order.sendGift" v-bind:false-value="order.dontSendGift" v-model="order.gift">
<label for="gift">Ship As Gift?</label>
</div>
</div>
<!-- end of form-group -->
<div class="form-group">
<div class="col-md-6 boxes">
<input type="radio" id="home" v-bind:value="order.home" v-model="order.method">
<label for="home">Home</label>
<input type="radio" id="business" v-bind:value="order.business" v-model="order.method">
<label for="business">Business</label>
</div>
</div>
<!-- end of form-group-->
<div class="form-group">
<div class="col-md-6">
<button type="submit" class="btn btn-primary submit" v-on:click="submitForm">Place Order</button>
</div>
<!-- end of col-md-6-->
</div>
<!-- end of form-group-->
<div class="col-md-12 verify">
<pre>
First Name: {{order.firstName}}
Last Name: {{order.lastName}}
Address: {{order.address}}
City: {{order.city}}
Zip: {{order.zip}}
State: {{order.state}}
Method: {{order.method}}
Gift: {{order.gift}}
</pre>
</div>
<!-- end of col-md-12 verify-->
</div>
<!--end of panel-body-->
</div>
<!--end of panel panel-info-->
</div>
<!--end of col-md-10 col-md-offset-1-->
</div>
<!--end of row-->
</div>
</main>
</div>
<!-- end of app-->
</div>
<script type="text/javascript">
var APP_LOG_LIFECYCLE_EVENTS = true;
var webstore = new Vue({
el: '#app',
data: {
sitename: "Vue.js Pet Depot",
showProduct: true,
a: false,
states: {
AL: 'Alabama',
AK: 'Alaska',
AR: 'Arizona',
CA: 'California',
NV: 'Nevada'
},
order: {
firstName: '',
lastName: '',
address: '',
city: '',
zip: '',
state: '',
method: 'Home Address',
business: 'Business Address',
home: 'Home Address',
gift: '',
sendGift: 'Send As A Gift',
dontSendGift: 'Do Not Send As A Gift'
},
products: {},
cart: []
},
methods: {
checkRating(n, myProduct) {
return myProduct.rating - n >= 0;
},
addToCart(aProduct) {
this.cart.push(aProduct.id);
},
showCheckout() {
this.showProduct = this.showProduct ? false : true;
},
submitForm() {
alert('Submitted');
},
canAddToCart(aProduct) {
//return this.product.availableInventory > this.cartItemCount;
return aProduct.availableInventory > this.cartCount(aProduct.id);
},
cartCount(id) {
let count = 0;
for (var i = 0; i < this.cart.length; i++) {
if (this.cart[i] === id) {
count++;
}
}
return count;
}
},
computed: {
cartItemCount() {
return this.cart.length || '';
},
sortedProducts() {
if (this.products.length > 0) {
let productsArray = this.products.slice(0);
function compare(a, b) {
if (a.title.toLowerCase() < b.title.toLowerCase())
return -1;
if (a.title.toLowerCase() > b.title.toLowerCase())
return 1;
return 0;
}
return productsArray.sort(compare);
}
}
},
filters: {
formatPrice(price) { //#B
if (!parseInt(price)) {
return "";
} //#C
if (price > 99999) { //#D
var priceString = (price / 100).toFixed(2); //#E
var priceArray = priceString.split("").reverse(); //#F
var index = 3; //#F
while (priceArray.length > index + 3) { //#F
priceArray.splice(index + 3, 0, ","); //#F
index += 4; //#F
} //#F
return "$" + priceArray.reverse().join(""); //#G
} else {
return "$" + (price / 100).toFixed(2); //#H
}
}
},
created: function() { //#C
axios.get('https://raw.githubusercontent.com/ErikCH/VuejsInActionCode/master/chapter-05/products.json')
.then((response) => {
this.products = response.data.products;
// console.log(this.products);
});
}
});
</script>
</body>
</html>

How to show error message on each input type field in nodejs using express-validator

I am begginer in nodejs and I am using express-validator library to validate form.
I want to display error message seprately to each input type field,
not group wise.
Currently my code shows the error in group like
Name is required!
Email is required!
Email is wrong!
Mobile is required!
========================================================================
Controller Code
employeeController.saveEmployee = function(req,res){
var employeeData = req.body;
// Start Validation
req.checkBody('employeeName','Name is required!').notEmpty();
req.checkBody('employeeEmail','Email is required!').notEmpty();
req.checkBody('employeeEmail','Email is wrong!').isEmail();
req.checkBody('employeeMobile','Mobile is required!').notEmpty();
req.sanitize('employeeName').trim();
req.sanitize('employeeName').escape();
// End Validation
var errors = req.validationErrors();
console.log(errors);
if(!errors){
var employee = new Employee({
name : req.body.employeeName,
email : req.body.employeeEmail,
mobile : req.body.employeemobile,
});
employee.save(function(err){
if(err){
throw err;
}
console.log('User inserted successfully');
res.redirect('/employee-list');
});
}else{
console.log(employeeData.employeeName);
res.render('employee/add-employee',{
errors : errors,
employeeData : employeeData
});
}
};
View template
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add Employee Profile</h3>
<h5 class='text-aqua pull-right' style='margin-top: 0px;'>
<i class="fa fa-backward"></i> Back
</h5>
</div>
<p>
<% if(errors){ %>
<ul>
<% for(var i = 0; i < errors.length; i++){ %>
<li> <%= errors[i].msg %> </li>
<% } %>
</ul>
<% } %>
</p>
<!-- form start -->
<form method = 'post' action = '/save-employee'>
<div class="box-body">
<div class="form-group col-md-4">
<label>Name</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeName' id='employeeName' value='<%= employeeData.employeeName %>' class='form-control' placeholder='Employee Name'>
</div>
</div>
<div class="form-group col-md-4">
<label>Email</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeEmail' id='employeeEmail' value='<%= employeeData.employeeEmail %>' class='form-control' placeholder='Employee Email'>
</div>
</div>
<div class="form-group col-md-4">
<label>Mobile</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeMobile' id='employeeMobile' value='<%= employeeData.employeeMobile %>' class='form-control' placeholder='Employee Mobile'>
</div>
</div>
</div>
<div class="callout" id='message-container' style='display:none;'></div>
<div class="box-footer">
<button type='submit' name='saveEmployeeProfile' class='btn btn-primary'>Save</button>
</div>
</form>
</div>
</div>
Ok, so what you have to do - is separate errors.
Your controller file:
employeeController.saveEmployee = function(req,res){
const nameRequired = 'Name is required!';
const emailRequired = 'Email is required!';
const emailNotValid = 'Email is wrong!';
const mobileRequired = 'Mobile is required!';
const employeeData = req.body;
// Start Validation
req.checkBody('employeeName', nameRequired).notEmpty();
req.checkBody('employeeEmail', emailRequired).notEmpty();
req.checkBody('employeeEmail', emailNotValid).isEmail();
req.checkBody('employeeMobile', mobileRequired).notEmpty();
req.sanitize('employeeName').trim();
req.sanitize('employeeName').escape();
// End Validation
const errors = req.validationErrors();
console.log(errors);
if(!errors){
const employee = new Employee({
name : req.body.employeeName,
email : req.body.employeeEmail,
mobile : req.body.employeemobile,
});
employee.save(function(err){
if(err){
throw err;
}
console.log('User inserted successfully');
res.redirect('/employee-list');
});
}else{
console.log(employeeData.employeeName);
const employeeNameRequired = errors.find(el => el === nameRequired );
const employeeEmailRequired = errors.find(el => el === emailRequired);
const employeeEmailNotValid = errors.find(el => el === emailNotValid);
const employeeMobileRequired = errors.find(el => el === mobileRequired);
res.render('employee/add-employee',{
employeeData,
employeeNameRequired,
employeeEmailRequired,
employeeEmailNotValid,
employeeMobileRequired
});
}
};
And you View file will look something like this:
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add Employee Profile</h3>
<h5 class='text-aqua pull-right' style='margin-top: 0px;'>
<i class="fa fa-backward"></i> Back
</h5>
</div>
<!-- form start -->
<form method = 'post' action = '/save-employee'>
<div class="box-body">
<div class="form-group col-md-4">
<label>Name</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeName' id='employeeName' value='<%= employeeData.employeeName %>' class='form-control' placeholder='Employee Name'>
<p><%= employeeNameRequired %></p>
</div>
<div class="form-group has-error">
<span class="help-block" style="text-align:center" id="error_tagType"></span>
</div>
</div>
<div class="form-group col-md-4">
<label>Email</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeEmail' id='employeeEmail' value='<%= employeeData.employeeEmail %>' class='form-control' placeholder='Employee Email'>
<p><%= employeeEmailRequired %></p>
<p><%= employeeEmailNotValid %></p>
</div>
<div class="form-group has-error">
<span class="help-block" style="text-align:center" id="error_tagName"></span>
</div>
</div>
<div class="form-group col-md-4">
<label>Mobile</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeMobile' id='employeeMobile' value='<%= employeeData.employeeMobile %>' class='form-control' placeholder='Employee Mobile'>
<p><%= employeeMobileRequired %></p>
</div>
<div class="form-group has-error">
<span class="help-block" style="text-align:center" id="error_tagDescription"></span>
</div>
</div>
</div>
<div class="callout" id='message-container' style='display:none;'></div>
<div class="box-footer">
<button type='submit' name='saveEmployeeProfile' class='btn btn-primary'>Save</button>
</div>
</form>
</div>
</div>
Update:
For me personally, using jsonSchema validation fits best. It's very configurable and results in more readable code. For example module tv4 can be used with jsonSchema to validate req.body.

how to display a single prouct from database in mongodb and node.js

we have created a e-commerce project in that while clicking on categories in UI it will renders to category page in that page it has show one product of each subcategory
i have written the code in which the entire products with the specific category name is displaying how i can remove the extra products as of now i required only one product of each sub category of the particular category
the routing code is
router.get("/shop/:category_name", function(req, res){
//querystring
var url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var viewModel = {
breadCrumb: [],
categories : [],
featuredProducts :[],
products : [],
};
viewModel.breadCrumb.push({
name : 'Home',
class : 'breadcrumb-ordinary'
});
viewModel.breadCrumb.push({
name : req.params.category_name,
class : 'breadcrumb-active'
});
async.parallel({
categories: function(cb){
Category.find({}, cb);
},
categories1:function(cb){
Category.find({category_name:req.params.category_name}, cb);
}
}, function(err, results) {
if (err) throw err;
viewModel.categories1=results.categories1;
viewModel.categories=results.categories;
res.render('shop/prod_grid',viewModel);
});
});
the view UI code is
<!doctype html>
<html lang="en-US"> <!--<![endif]-->
<head>
</head>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="../../../shop-plugins/css/jplist-pagination.css">
<link rel="stylesheet" href="../../../shop-plugins/css/breadcrumb.css">
<body>
{{> shop/header}}
<!-- BAR -->
<div class="shipping-wrap">
<div class="container">
<div class="row">
<div class="span12">
<ul>
<li>
{{#each breadCrumb}}
{{#if #first}}
<a href="/" class="{{class}}">{{name}}
{{else}}
<a class="{{class}}">{{name}}
{{/if}}
{{#if #last}}
{{else}}
<i class="fa fa-angle-double-right"></i></a>
{{/if}}
{{/each}}
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- BAR -->
<!-- PRODUCT-OFFER -->
<div class="product_wrap">
<div class="container">
<div class="row">
<div id="span9" class="span9 product-grid">
<div id="products" class="box jplist jplist-grid-view">
<div class="jplist-panel box jplist-panel-top">
<div
class="jplist-drop-down"
data-control-type="items-per-page-drop-down"
data-control-name="paging"
data-control-action="paging">
<ul id="per-pages">
<li><span data-number="3">3 per page</span></li>
<li><span data-number="6" data-default="true">6 per page</span></li>
<li><span data-number="9">9 per page</span></li>
<li><span data-number="12">12 per page</span></li>
</ul>
</div>
<div
class="jplist-drop-down"
data-control-type="sort-drop-down"
data-control-name="sort"
data-control-action="sort">
<ul id="sorting">
<li><span data-path="default">Sort By</span></li>
<li><span data-path=".brand" data-order="asc" data-type="text">Brand A-Z</span></li>
<li><span data-path=".brand" data-order="desc" data-type="text">Brand Z-A</span></li>
<li><span data-path=".cost" data-order="asc" data-type="number">Cost Low-High</span></li>
<li><span data-path=".cost" data-order="desc" data-type="number">Cost High-Low</span></li>
</ul>
</div>
<div
class="jplist-label"
data-type="Page {current} of {pages}"
data-control-type="pagination-info"
data-control-name="paging"
data-control-action="paging">
</div>
<div
class="jplist-views"
data-control-type="views"
data-control-name="views"
data-control-action="views"
data-default="jplist-grid-view">
</div>
</div>
{{#each subcategoryprod}}
<div>
<ul>
<li>{{subcategory}}</li>
</ul>
</div>
{{/each}}
<!--category wise products-->
<div id="jp-panel" class="list box text_shadow">
{{#each subcategoryprod}}
<div id="jp-panel-item" class="list-item box">
<div class="span3 product">
<div>
<figure>
{{#each image}}
{{#if #first}}
<img src="../../../uploads/products/{{../_id}}/{{img}}" alt="" onerror="this.src='../../../shop-images/coming-soon.png'">
<div class="overlay">
</div>
{{/if}}
{{else}}
<img src="../../../shop-images/coming-soon.png" alt="">
<div class="overlay">
</div>
{{/each}}
</figure>
<div class="detail">
<span name="retailprice" class="cost">₹{{RetailPrice}}</span>
<span>{{colour}}</span>
<h4 class="brand">{{brand}}</h4>
<span>{{Description}}</span>
<div class="icon">
</div>
</div>
</div>
</div>
</div>
{{/each}}
</div>
<div class="box jplist-no-results text-shadow align-center">
<p> No results Found</p>
</div>
<div class="jplist-panel box panel-bottom">
<div
class="jplist-label"
data-type="{start} - {end} of {all}"
data-control-type="pagination-info"
data-control-name="paging"
data-control-action="paging">
</div>
<div
class="jplist-pagination back-top"
data-control-animate-to-top="true"
data-control-type="pagination"
data-control-name="paging"
data-control-action="paging">
</div>
</div>
</div>
</div>
<div class="span3">
<div class="row">
</div>
<div id="sidebar">
<div class="widget">
<h4>Price Filter</h4>
<div class="price-range">
<div id="slider-range"></div>
<p class="clearfix">
<input type="text" id="amount" readonly />
<input type="text" id="amount2" readonly />
</p>
</div>
</div>
<div class="widget">
<h4>BRANDS</h4>
<div id="">
<div class="brands">
<input type='text' id='txtList' onkeyup="searchBrand(this)" placeholder="search brands here....." />
<!-- <ul id="fromList" class="myid"> -->
{{#each products}}
<ul id="fromList" class="myid">
<li> <input type="checkbox" id="{{brand}}" class="brandFilterCheckBox pull-right" align="center"/> <label for="{{brand}}">{{brand}}<label></li>
</ul>
{{/each}}
<!-- </ul> -->
</div>
</div>
</div>
</div>
<div class="widget">
<h4>CATEGORIES</h4>
<div id="accordion">
{{#each categories}}
<h5>{{category_name }}</h5>
<div>
<ul>
{{#each subcategories1}}
<li>{{subcategory_name}}</li>
{{/each}}
</ul>
</div>
{{/each}}
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Featured Products -->
<div class="container" style="margin-top:10px">
<div class="row heading-wrap">
<div class="span12 heading">
<h2>Featured Products <span></span></h2>
</div>
</div>
<div class="row similar_products">
<div id="feat_prod">
{{#each featuredProducts}}
<div class="span3 product">
<figure>
{{#each image}}
{{#if #first}}
<img src="../../../uploads/products/{{../_id}}/{{img}}" alt="">
<div class="overlay">
</div>
{{/if}}
{{/each}}
</figure>
<div class="detail">
<span>₹{{RetailPrice}}</span>
<h4>{{product_name}}</h4>
<span>{{Description}}</span>
</div>
</div>
{{/each}}
</div>
</div>
</div>
<!-- PRODUCT-OFFER -->
<!-- FOOTER -->
{{> shop/footer}}
<script type="text/javascript" src="../../../shop-plugins/js/jplist-pagination.js"></script>
<script src="../../../bootstrap/js/star.min.js"></script>
<script src="../../../shop-plugins/js/jquery.paginate.js"> </script>
<script>
$(function(){
$('#feat_prod').paginate();
});
</script>
<script>
$(document).ready(function(){
$('#products').jplist({
itemsBox: '.list'
,itemPath: '.list-item'
,panelPath: '.jplist-panel'
});
});
</script>
<script>
$('document').ready(function(){
$("#slider-range").slider({change : function(event,ui){
var lowerLimit=$("#amount").val();
var numberLowerLimit=Number(lowerLimit.substring(1,lowerLimit.length));
var upperLimit=$("#amount2").val();
upperLimit=upperLimit.substring(1,upperLimit.length);
var numberUpperLimit=Number(upperLimit.replace("₹",""));
console.log("LOWER LIMIT :"+lowerLimit+" UPPER LIMIT :"+upperLimit);
$(".cost").each(function(){
var rowUnitCost=$(this).text();
var unitCost=Number(rowUnitCost.substring(1,rowUnitCost.length));
if(unitCost<numberLowerLimit || unitCost>numberUpperLimit){
var hiddingBox=$(this).parents(".list-item");
/*hiddingBox.removeClass("list-item").addClass("rafsal-test");*/
hiddingBox.hide();
console.log("Values IN:"+unitCost);
}
else{
var hiddingBox=$(this).parents(".list-item");
if(hiddingBox.attr('id')==undefined || hiddingBox.attr('id')=="undefined"){
hiddingBox=$(this).parents(".rafsal-test");
hiddingBox.addClass("list-item").removeClass("rafsal-test");
}
hiddingBox.show();
console.log("Values OUT:"+unitCost);
}
$('#products').jplist({
itemsBox: '.list' ,
itemPath: '.list-item' ,
panelPath: '.jplist-panel'
});
});
}
});
// Brand Filter
$(".brandFilterCheckBox").on('click',function(){
$(".brand").each(function(){
var hiddingBox=$(this).parents(".list-item");
hiddingBox.removeClass("list-item").addClass("rafsal-test");
hiddingBox.hide();
});
$(".brandFilterCheckBox").each(function(){
if($(this).prop("checked")){
var filterBrand=$(this).attr("id");
$(".brand").each(function(){
var unitBrandName=$(this).text().trim();
if(unitBrandName== filterBrand){
console.log(unitBrandName);
var hiddingBox=$(this).parents(".list-item");
if(hiddingBox.attr('id')==undefined || hiddingBox.attr('id')=="undefined"){
hiddingBox=$(this).parents(".rafsal-test");
hiddingBox.addClass("list-item").removeClass("rafsal-test");
}
hiddingBox.show();
}
});
$('#products').jplist({
itemsBox: '.list' ,
itemPath: '.list-item' ,
panelPath: '.jplist-panel'
});
}
});
})
var textCheck="##";
removeDuplicateBrands()
});
function removeDuplicateBrands(){
var textCheck="##";
$(".brandFilterCheckBox").each(function(){
$(this).attr('id');
if(textCheck.indexOf("##"+$(this).attr('id')+"##")==(-1)){
textCheck=textCheck+$(this).attr('id')+"##";
}
else{
$(this).parent("li").hide();
}
});
}
</script>
<script>
function searchBrand(element) {
var value = $(element).val();
$("#fromList li").each(function () {
if ($(this).text().search(value) > -1) {
$(this).show();
$(this).prevAll('.header').first().show();
} else {
$(this).hide();
}
});
removeDuplicateBrands();
}
</script>
</body>
so i am posting a photo in which my output is there it contains all products of a specified category i need only one product from each sub category of the specified category and the image contains four products of protection category and two sub categories air freshners and Head unit , air freshners contains three products i need to display only one from airfreshner and one from head unit in which we need
In Your Router Code, Edit this section
categories1:function(cb){
Category.find({category_name:req.params.category_name}, cb);
}
Change the above to this
categories1:function(cb){
Category.findOne({category_name:req.params.category_name}, cb);
}
That should solve it for you.

No data send with socket.io

I have to send data using socket.io.when a user enter his login and a password,he will be redirect to index.ejs and the username will be send to the server.
route.js (I mentioned only the part of the script not the hole script to show that when the login and password are correct a user get an index page and the userobject send to the index):
var index = function(req, res, next) {
if(!req.isAuthenticated()) {
res.redirect('/signin');
} else {
var user = req.user;
if(user !== undefined) {
user = user.toJSON();
}
res.render('index', {title: 'Home', user: user});
}
};
app.js:
io.sockets.on('connection', function (socket) {
socket.on("new_user",function(user1){
console.log("a new user is connected",user1);
var current_date=new Date();
var date=current_date.toString();
ex.user_connect(user1,date);
});
});
index.ejs:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width ,initial-scale=1.0" />
<title><%= title %></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style/style.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">HomePage</a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><%= user.username%></li>
<li><span class="glyphicon glyphicon-log-out"></span> Sign out</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-sm-6">
<div class="container">
<h2>Led1</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-default btn-lg" id="led1" align="center">check it</button>
<!-- Modal -->
<div class="modal fade" id="model_led1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal" id="close">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Settings</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form">
<img src="style/images/led.png" id="led" class="img-responsive"/>
<button type="button" class="btn btn-success btn-block" id="led1_activ"><span class="glyphicon glyphicon-off"></span> Activate</button>
<button type="button" class="btn btn-success btn-block" id="led1_desactiv"><span class="glyphicon glyphicon-off"></span> Desactivate</button>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal" id="cancel_button"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
var user1 = user.username;
socket.emit('new_user',user1);
</script>
NB:I got the username on the navbar but I don't get it on the server console.
Ejs render all template variables in server and then return plain html to the client , so
Inside your script , do you have variable global user initialized? :
var user1 = user.username // var user = {username:"foo":} ,something like that before.
If you trying to get user from template variable you could try:
var user1= "<%= user.username%>";
This will render <%= user.username%> inside script tag before send to the client ( browser)

Resources