Simple To-Do app just doesn't print to-dos - node.js

I am building a simple To Do application Using node js, express, mongodb and ejs.
My get Route renders the form and the post route handles post request on the form, they both work perfect, any time I insert a (todo) it gets saved and can be found in my Mongo compass.
But it does not appear on the screen as Todo App should be. It only prints out usual bullets of (ul). I don't know what I am doing wrong, here is my code:
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const session = require('express-session');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/Todo-App",
{useUnifiedTopology:true,useNewUrlParser:true,useFindAndModify:false,useCreateIndex:true});
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret:"secret"}));
var todoschema = mongoose.Schema({
item:String,
});
var Todo = mongoose.model("Todo",todoschema);
app.get('/',(req,res)=>{
res.render('home.ejs',{Todo:Todo});
});
app.post('/',(req,res)=>{
var newTodo = new Todo({
item:req.body.item,
});
newTodo.save((err,result)=>{
if(err){
throw err;
}
else{
res.redirect('/');
}
})
})
app.listen(8080,()=>{
console.log("App is running...")
})
Here is my code in the ejs file
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>My To-Do Application</h1>
<form action="/" method="post">
<input type="text" name="item" placeholder="Enter Item">
<input type="submit" value="Add To List">
</form>
<%for(var i = 0; i < Todo.length; i++){%>
<li> <%=Todo[i]%></li>
<%}%>
</body>
</html>

I think the issue is here
app.get('/', (req, res) => {
res.render('home.ejs', { Todo : Todo });
});
you are doing the res.render without finding the documents from db
I think we need to add a find query before doing res.render
it should be something like that
app.get('/', (req, res) => {
Todo.find({}, (err, todos) => { // passing an empty object as a first argument to the find method means we need to get all the documents from Todo collection
if (err) {
throw err;
} else {
res.render('home.ejs', { Todo: todos });
}
});
});
hope it helps

Related

Why won't any of my http methods work from my new router folder? and how can I fix it?

This is my first web dev project. I am basically trying to make a simple website to sell light sabers. The goal is to be able to create an account, login, add, edit and delete light sabers. Be able to add them to cart and checkout. I am using node.js, express, and mongoDB in visual studio code. I am also learning github throughout the process. As of now I have the layout of the website mostly set up. Am able to create accounts and login. I am currently stuck on creating items(light sabers) and saving them in the mongoDB database. Specifically my http methods in the routes/items files are not working, they were working previously in the app.js file but I decided to move everything for organizational purposes. Again, this is my first time working with any of this tech and this project is a work in progress, any input is appreciated. Thanks.
Here is my code: There is a lot of code not being used and its kind of a mess. I know..
app.js file:
const express = require("express");
const session = require("express-session");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require('body-parser');
var localStrategy = require('passport-local');
var passportLocalMongoose = require("passport-local-mongoose");
var router = express.Router();
const app = express();
const indexRouter = require('./routes/index')
const itemsRouter = require('./routes/items')
//npm install ejs body-parser mongoose passport passport
var uri = "mongodb://username:password#cluster0-shard-00-00-
hnxfk.mongodb.net:27017,cluster0-shard-00-01-
hnxfk.mongodb.net:27017,cluster0-shard-00-02-
hnxfk.mongodb.net:27017/test?
ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority";
var localHost = "mongodb://localhost:27017/Project2SamJoshEricRoy"
mongoose.connect(uri,{useNewUrlParser: true, useUnifiedTopology:
true });
var User = require('./models/user');
var Item = require('./models/item');
// var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(require('express-session')({
secret: "application secret shhhh",
resave: false,
saveUninitialized: false
}));
passport.use(new localStrategy(User.authenticate()))
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter)
app.use('/items', itemsRouter)
//create account
app.get("/createAccount",(req,res)=> {
res.render("createAccount");
});
app.get('/createAccount', function(req,res) {
res.render('createAccount');
});
app.post("/createAccount",(req,res)=> {
req.body.username;
req.body.password;
User.register(new
User({username:req.body.username}),req.body.password,
(err,user) =>{
if(err) {
console.log(err);
return res.render("createAccount");
}
passport.authenticate("local")(req,res,() => {
res.redirect('/login');
console.log(req.body.username
+ " " + req.body.password);
console.log(user);
});
});
});
//login
app.get("/login",(req,res) => {
res.render("login")
User.find(function(err,users) {
if(err) {
console.log(err);
}
// console.log(users);
})
});
app.post('/login',passport.authenticate("local",{
successRedirect: "/lightsabers",
failureRedirect: "/login"
}),(req,res)=> {
});
function isLoggedIn(req,res,next) {
console.log("CALL")
if(req.isAuthenticated()) {
console.log("logged in ");
return next();
}
res.redirect("/login");
console.log("error logging in");
}
//logout
app.get("/logout",(req,res)=> {
req.logout();
res.redirect('/');
});
//lightsabers
//app.get("/lightsabers",isLoggedIn,(req,res)=> {
//res.render("lightsabers",{user: req.user});
//console.log(req.user);
//});
//shopping cart
app.get("/cart",(req,res)=> {
res.render("cart");
});
app.get('/createLightsaber',(req,res)=> {
res.render("newItem",{user:req.User});
console.log("user is with us");
console.log(req.user)
});
app.get('/updateItem',(req,res)=> {
res.render("updateLightsaber");
});
app.get('/deleteLightsaber',(req,res)=> {
res.render("updateLightsaber");
});
/routes/index.js file:
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.render('index')
})
module.exports = router
routes/items.js
const express = require('express')
const router = express.Router()
const Item = require('../models/item')
//display page
router.get("/",(req,res)=> {
res.render("newItem");
});
// all items route
router.get('/', async (req, res) =>{
try{
const items = await Item.find({})
res.render('items/newItem', {item: new Item() })
} catch {
res.redirect('/')
}
})
//new item route (display form)
router.get('/newItem', (req, res) => {
res.render('items/newItem', {item: new Item() })
})
// create new item route (actual creation)
router.post('/newItem', async (req,res) => {
const item = new Item({
color:req.body.color,
price:req.body.price,
link:req.body.link
})
try{
const newItem = await item.save()
res.redirect('lightsabers')
} catch {
res.render('items/newItem', {
item: item,
errorMessage:'Error creating item'
})
}
})
/update item
app.get("/updateItem",(req,res)=> {
res.render("updateItem");
});
module.exports = router
newItem.ejs
<!DOCTYPE html>
<html>
<head>
<title> </title>
<link rel="stylesheet" href="/css/styles.css"/>
</head>
<body>
<h1> Adding New Item </h1>
<form action="/items" method="POST">
<h2>
Color: <input type="text" name="color"><br>
Price: <input type="text" name="price"><br>
Image Link:<input type="text" name="link"><br>
<br><br>
<button id="addItem">Add Item</button>
<%= typeof(message) != "undefined"?message:"" %>
</h2>
</form>
<form action="/lightsabers">
<h2><button> Back </button></h2>
</form>
<script type="text/javascript" src="../public/app.js">
</script>
</body>
</html>
If you wish to see any other parts of the code let me know. I may be forgetting something important.

Show Image file using NodeJS

Using node.js and mongodb I want to upload image and show that image using it's id.
but When i run it, showing an error..
Error: Failed to lookup view "/showImage" in views directory "H:\NodeJS\AddImage
\views"
searching a lot but couldn't find any proper and working solution for me.
what's the problem??
can anyone help??
thanks..
here is my code...........
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
var multer = require('multer');
app.use(bodyParser.json());
app.use(express.static('public'));
var imagefile = require('./routes/imagefile');
app.set('view engine', 'ejs');
mongoose.connect('mongodb:..url');
imagefile(app);
app.listen(3000);
console.log('Running on port 3000');
imagefile.js
var express = require('express');
var multer = require('multer');
var mongoose = require('mongoose');
var fs = require('fs');
var imageSchema = mongoose.Schema({
img: { data: Buffer, contentType: String },
imageName : String
});
var Item = mongoose.model('Clothes',imageSchema);
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'public/')
},
filename: function(req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({
storage: storage
});
module.exports = function (app) {
app.get('/', function(req, res, next) {
res.render('index.ejs');
});
app.get('/images/:id', function(req, res) {
Item.findById(req.params.id, function (error, result) {
//res.contentType(result.contentType);
console.log(result.imageName);
//res.end(result.image.buffer, "binary");
res.render('/showImage',{imageName : result.imageName, imageId : result.imageName});
});
});
app.post('/', upload.any(), function(req, res, next) {
var newItem = new Item();
newItem.img.data = fs.readFileSync(req.files[0].path)
newItem.img.contentType = 'image/png';
newItem.imageName = req.files[0].originalname;
newItem.save();
res.render('index.ejs');
});
};
index.ejs
<html>
<head>
<title>test</title>
</head>
<body>
<form action "/" method="POST" enctype="multipart/form-data">
<input type="file" name="myimage" ></input>
<input type="submit" name="submit" value="submit"></input>
</form>
</body>
</html>
showImage.ejs
<html>
<head>
<title>test</title>
</head>
<body>
<h1><%= imageName %></h1>
<h1><%= imageId %></h1>
<div class="header">
<img src='/public/36417514_2140268509321308_7450232816341614592_n.jpg %>' />
</div>
</body>
</html>
Remove the leading slash in this function:
app.get('/images/:id', function(req, res) {
// Rest of the code
// ...
res.render('showImage', // <-- Remove slash
{imageName : result.imageName, imageId : result.imageName});
});
});
the problem is that it looks for file named '/showImage.ejs'.

I'm stuck in rendering templates using express and handlebars

Please, explain me, why my code does not work?
I'm using express width handlebars, for form submit using Jquery Ajax. First render works properly, but second does not. I think that the problem is in nesting 'res.render'. Hope on your answers :-)
app.js
var express = require('express');
var app = express();
var template = require('consolidate');
var handlebars = require('handlebars');
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: false}));
app.engine('hbs', template.handlebars);
app.set('view engine', 'hbs');
app.set('views', __dirname);
app.get('/', function(req, res) {
res.render('index', {
myName: 'John'
});
});
app.post('/', function(req, res) {
var obj = {surname: req.body.surname, age: req.body.age};
res.render('Layout.hbs', obj, function(err, html) {
if(err) {
console.log(err);
} else {
console.log(html);
res.render('index.hbs', {
content: html
})
}
}
);
});
app.listen(8080, function() {
console.log('App listening on 8080');
});
index.hbs
<div class="wrapper">
<div class="container">
<p>{{myName}}</p>
</div>
<form action="" name="form" id="form" method="post">
<input id="surname" type="text" name="surname" placeholder="surname"><br/>
<input id="age" type="text" name="age" placeholder="age"><br/>
<input type="submit">
</form>
{{{content}}}
</div>
<script type="text/javascript">
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var surname = form.find('#surname').val();
var age = form.find('#age').val();
$.ajax({
type: 'POST',
data: {surname: surname, age: age},
success: function(res) {
console.log('Success');
},
error: function(err) {
console.log(err);
}
});
});
});
</script>
Layout.hbs
<div class="inner-container">
<h1>{{surname}}</h1>
<h2>{{age}}</h2>
<p>Render</p>
</div>
I think you are right, the problem is with nested res.render. When you call res.render, it renders a html and sends it to the client with a status code of 200.
You can call app.render on root level and res.render only inside a route/middleware. But keep in mind, res.render uses app.render internally to render template files. I don't think there is any need of rendering template separately.
Hope the answer helps you. It would be better for me to answer if I could see the error log that you are getting. If you provide that I would change my answer accordingly.
I think issue with binding delegation event with on() method..
$('form').on('submit', function(e) {
Replace it by
$(document).on('submit','form', function(e)){

Database is not creating using express and node.js

I am working on simple registration page using express and mongodb this is my html
<body>
<form>
<div align="center" ng-controller="regiCtrl">
<table>
<tr>
<td>User Name :</td>
<td><input type="text" ng-model="user.userName" />
</td></tr>
<tr>
<td>Password :</td>
<td><input type="password" ng-model="user.password" />
</td></tr>
<tr>
<tr><td>
<input type="button" value = "Submit" ng-click="regi()"></td>
<td>
</td></tr>
</table>
</div>
</form>
</body>
and this is my controller
lyfee.controller('regiCtrl',['$scope','$http', function($scope,$http) {
$scope.user = {};
$scope.regi = function () {
// var data = {User: $scope.user }
console.log($scope.user);
$http.post('/regi',$scope.user);
console.log("post request send");
}
}]);
have a look of my server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
//Used for open index.html by default(open html page which one will be in public folder)
app.use(express.static(__dirname + "/public"));
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: 'anystringoftext',
saveUninitialized: true,
resave: true}));
app.use('/', function(req, res){
//res.send('Our First Express program!');
//res.redirect('index.html');
//console.log(req.cookies);
// console.log(req.session);
console.log("HELLO WE ARE IN SERVER");
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/lyfee_module');
console.log("Connection created");
var Userschema = require('./models/dbSchema');
app.post('/regi',function(req,res){
console.log("post request get");
/*
var schema = new Userschema();
schema.Firstname = req.body.Firstname;
schema.Lastname = req.body.Lastname;
schema.City = req.body.city;
schema.Email = req.body.email;
schema.Userid = req.body.userid;
schema.Password = req.body.password;
console.log(schema.Firstname);
// console.log(schema.Lastname);
*/
console.log(req);
var schema = new Userschema({
userName : req.body.userName,
password : req.body.password,
});
console.log(req.body);
console.log(schema);
schema.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Record Inserted', userName: req.body.userName, password: req.body.password});
});
});
app.listen(port);
console.log('Server running on port: ' + port);
it's my config.js
module.export = {
'secret' : 'lyfee',
'database': 'mongodb://localhost/lyfee_module'
};
and finally is my db
var mongoose = require('mongoose');
var User = new mongoose.Schema({
userName: String,
password: String,
});
//console.log(User);
module.exports = mongoose.model('user', User);
my entries is not storing in database even database with lyfee_module is not creating please help me, how to i can solve this problem ?
i think every thing is looking fine just add running port of mongodb in config.js like
mongodb://localhost:27017/
Have you tried using a callback with mongoose.connect()? I would recommend trying the following and see if you get any errors:
mongoose.connect(mongoUrl, err => {
console.log(err || `MongoDB connected at ${mongoUrl}`);
})

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

Resources