Second ejs file not picking data Nodejs - mysql

So, basically I am trying to link two ejs files to express. The first one gets connected and displays result but second one that comes after pressing a button on first one shows error.
The user-list file displays results correctly but the exact same table code shows error in parks
parks.ejs (when I click the link in user-list that redirects here, it says userData not defined)
<div class="table-data">
<h2>Display Data using Node.js & MySQL</h2>
<table>
<tr>
<th>ID</th>
<th>Station N</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<%
if(userData.length!=0){
var i=1;
userData.forEach(function(data){
%>
<tr>
<td><%=i; %></td>
<td><%=data.Station %></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<% i++; }) %>
<% } else{ %>
<tr>
<td colspan="7">No Data Found</td>
</tr>
<% } %>
</table>
</div>
user-list.ejs
hello
++the table code shown above
users.js
var express = require('express');
var router = express.Router();
var db = require('../database');
router.get('/user-list', function(req, res, next) {
db.query("SELECT Station_ID FROM Station WHERE Name = 'A'", function (err, results, fields) {
if (err) throw err;
res.render('user-list', { title: 'User List', userData: results});
});
});
router.get('/parks', function(req, res, next) { //this part not working
db.query("SELECT Station_ID FROM Station WHERE Name = 'A'", function (err, results, fields) {
if (err) throw err;
res.render('parks', { title: 'User Listt', userData: results});
});
});
module.exports = router;
Worth noting is the app.js file because there I had to add app.get("/parks" line to link the two pages otherwise even the link didn't redirect to parks.ejs
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const ejs = require('ejs');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// 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(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.get("/parks", function(req,res){
res.render("parks");
});
// 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;

hello
Here, the url is relative to the document root, so this will trigger your app.get("/parks") route handler - which actually doesn't seem to provide a userData variable.
If you want to trigger the router.get('/parks') handler from your user router, you should use a url relative to the current path.
hello
or
hello

Related

Posting API data to ejs using node-fetch

I have been having trouble with displaying the API information that I fetched using node-fetch. I want the data title, img, and etc to show in the ejs body, but I receive an error message from index.ejs saying currentData is not defined.
var express = require('express');
var fetch = require('node-fetch');
var app = express();
//Port information
const port = process.env.port || 3000;
//tell application to use ejs for templates
app.set('view engine', 'ejs');
//make styles public
app.use(express.static("public"));
app.get('/', function(req,res){
//return something to homepage
res.render('index');
});
app.get('/comic', function(req,res){
let currentData;
fetch('http://xkcd.com/info.0.json')
.then(res => res.json())
.then(data => {
curentData = data;
res.json(currentData);
});
});
//index.ejs file:
<div>
<form action ="/dailyInfo" method="POST">
<%= currentData.month %>
</div>

Keep getting CANNOT POST /login everytime i login

I got the codes from a tutorial, seems to work fine until I made routers since I'm trying to create an E-commerce website with a login system.
This is my index.js code
const express = require('express');
const app = express();
const prodRouter = require('./server/routes/prodRouter');
const loginRouter = require('./server/routes/loginRouter');
const regRouter = require('./server/routes/regRouter');
const contRouter = require('./server/routes/contRouter');
const checkRouter = require('./server/routes/checkRouter');
const profRouter = require('./server/routes/profRouter');
const path = require('path'); const port = 3500;
app.use(express.static('public'));
app.set('views', path.join(__dirname, 'server/views'));
app.set('viewengine', 'pug');
app.use('/prod', prodRouter);
app.use('/login',loginRouter);
app.use('/reg', regRouter);
app.use('/cont',contRouter);
app.use('/check', checkRouter);
app.use('/profile',profRouter);
app.get('/', (req, res) =>{res.render('Home.pug', {}); });
app.listen(port, (err) => { // arrow function feature from ES6 if(err){ console.log(err); }
console.log(`Listening to port ${port}!`); });
and loginRouter.js
const express = require('express'); const router = express.Router();
const app = express();
const mysql = require('mysql');
const server = require('http').createServer(app);
bodyParser = require('body-parser');
const connection = mysql.createConnection({
host: 'localhost',
database: 'login',
user: 'root',
password: '',
});
users = []; connections = [];
router.get('/', (req, res) => {
res.render('login', {});
});
app.use(bodyParser.urlencoded({
extended: true
});
app.use(bodyParser.json());
connection.connect();
app.post('/', function(req, res){
var email= req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM user WHERE email = ?',[email],function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if([0].password == password){
return res.redirect('/profile');
}else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}else{
res.send({
"code":204,
"success":"Email does not exits"
});
}
}
});
enter code here
});
module.exports = router;
my pug form:
form#login-form(method='post')
fieldset.input
p#login-form-username
label(for='modlgn_username') Email
input#modlgn_username.inputbox(type='text', name='email', size='18', required)
p#login-form-password
label(for='modlgn_passwd') Password
input#modlgn_passwd.inputbox(type='text', name='password', size='18', required)
.remember
p#login-form-remember
label(for='modlgn_remember')
a(href='#') Forget Your Password ?
input.button(type='submit', value='Sign In')
I'm pretty sure I did something wrong with the router, because every time I login, I keep getting CANNOT POST instead of going to the profile page.
Any help would be greatly appreciated.
EDIT: I added my pug code for form.
EDIT: the problem only occurs if the login page is not the main page.
example:
login page > *logs in > profile - no problem
home page > login page > *logs in > profile - error
This is happening because you don't have an action on your form (see this article for details). When you don't have an action the form is submitted to the URL it lives at, so if you POST on your home page without an action the post will go to /home.
Change the form element to look like this:
form#login-form(method='post' action='/login')

How to render node js data in html template?

I am unable to render data in html template but when I use express then inserted but file format is ejs . but I need listing my data in html without express. How to do that?
This is my server.js file here I have in this file database connection, insert record, select record and edit record query. Please see my code here is sjs templates.
Note: the problem is here is ejs templates but I want to render my nodejs code in .html format file not .ejs format.
server.js
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
emailExistence = require('email-existence'),
app = express(),
expressValidator = require('express-validator');
/*Set EJS template Engine*/
app.set('views','./views');
app.set('view engine','ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); //support x-www-form-urlencoded
app.use(bodyParser.json());
app.use(expressValidator());
/*MySql connection*/
var connection = require('express-myconnection'),
mysql = require('mysql');
app.use(
connection(mysql,{
host : 'localhost',
user : 'root',
password : '',
database : 'mydb',
debug : false //set true if you wanna see debug logger
},'request')
);
app.get('/',function(req,res){
res.send('Welcome');
});
//RESTful route
var router = express.Router();
/*------------------------------------------------------
* This is router middleware,invoked everytime
* we hit url /api and anything after /api
* like /api/user , /api/user/7
* we can use this for doing validation,authetication
* for every route started with /api
--------------------------------------------------------*/
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
var curut = router.route('/user');
//show the CRUD interface | GET
curut.get(function(req,res,next){
req.getConnection(function(err,conn){
if (err) return next("Cannot Connect");
var query = conn.query('SELECT * FROM t_user',function(err,rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.render('user',{title:"RESTful Crud Example",data:rows});
});
});
});
//post data to DB | POST
curut.post(function(req,res,next){
//validation
req.assert('name','Name is required').notEmpty();
req.assert('email','A valid email is required').isEmail();
req.assert('password','Enter a password 6 - 20').len(6,20);
var errors = req.validationErrors();
if(errors){
res.status(422).json(errors);
return;
}
//get data
var data = {
name:req.body.name,
email:req.body.email,
password:req.body.password
};
//inserting into mysql
req.getConnection(function (err, conn){
if (err) return next("Cannot Connect");
var query = conn.query("INSERT INTO t_user set ? ",data, function(err, rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.sendStatus(200);
});
});
});
//now for Single route (GET,DELETE,PUT)
var curut2 = router.route('/user/:user_id');
/*------------------------------------------------------
route.all is extremely useful. you can use it to do
stuffs for specific routes. for example you need to do
a validation everytime route /api/user/:user_id it hit.
remove curut2.all() if you dont want it
------------------------------------------------------*/
curut2.all(function(req,res,next){
console.log("You need to smth about curut2 Route ? Do it here");
console.log(req.params);
next();
});
//get data to update
curut2.get(function(req,res,next){
var user_id = req.params.user_id;
req.getConnection(function(err,conn){
if (err) return next("Cannot Connect");
var query = conn.query("SELECT * FROM t_user WHERE user_id = ? ",[user_id],function(err,rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
//if user not found
if(rows.length < 1)
return res.send("User Not found");
res.render('edit',{title:"Edit user",data:rows});
});
});
});
//update data
curut2.put(function(req,res,next){
var user_id = req.params.user_id;
//validation
req.assert('name','Name is required').notEmpty();
req.assert('email','A valid email is required').isEmail();
req.assert('password','Enter a password 6 - 20').len(6,20);
var errors = req.validationErrors();
if(errors){
res.status(422).json(errors);
return;
}
//get data
var data = {
name:req.body.name,
email:req.body.email,
password:req.body.password
};
//inserting into mysql
req.getConnection(function (err, conn){
if (err) return next("Cannot Connect");
var query = conn.query("UPDATE t_user set ? WHERE user_id = ? ",[data,user_id], function(err, rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.sendStatus(200);
});
});
});
//delete data
curut2.delete(function(req,res,next){
var user_id = req.params.user_id;
req.getConnection(function (err, conn) {
if (err) return next("Cannot Connect");
var query = conn.query("DELETE FROM t_user WHERE user_id = ? ",[user_id], function(err, rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.sendStatus(200);
});
//console.log(query.sql);
});
});
//now we need to apply our router here
app.use('/api', router);
//start Server
var server = app.listen(4000,function(){
console.log("Listening to port %s",server.address().port);
});
user.ejs
This is my ejs view template files
<!DOCTYPE html>
<html>
<head>
<title><%=title%></title>
<script type="text/javascript" src="/../js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/../js/all.js"></script>
<link rel="stylesheet" href="/../css/style.css">
</head>
<body>
<div class="data-table">
<table border="1" cellpadding="7" cellspacing="7">
<tr>
<th width="50px">No</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>Action</th>
</tr>
<% if(data.length){
for(var i = 0;i < data.length;i++) { %>
<tr>
<td><%=(i+1)%></td>
<td><%=data[i].name%></td>
<td><%=data[i].email%></td>
<td><%=data[i].password%></td>
<td>
<a class="a-inside edit" href="/api/user/<%=data[i].user_id%>">Edit</a>
<a class="a-inside delete" href="javascript:void(0)" onClick="deleteUser(<%=data[i].user_id%>)">Delete</a>
</td>
</tr>
<% }
}else{ %>
<tr>
<td colspan="5">No Data</td>
</tr>
<% } %>
</table>
</div>
<div class="page-data">
<form method="post" action="" id="the-form">
<table cellpadding="11">
<tr>
<td class="label">Name</td><td>: <input type="text" name="name"></td>
</tr>
<tr>
<td class="label">Email</td><td>: <input type="text" name="email"></td>
</tr>
<tr>
<td class="label">Password</td><td>: <input type="password" name="password"></td>
</tr>
<tr>
<td class="label"></td>
<td>
<input type="button" value="Save" onClick="saveUser()">
</td>
</tr>
</table>
</form>
</div>
<div class="page-data">
<ul class="err-area"></ul>
</div>
<script>
function saveUser(){
$.ajax({
url:"/api/user",
type:"post",
data:$("#the-form").serialize(),
success:function(res){
window.location.reload();
return false;
},
error:function(xhr, status, error){
console.log(xhr.responseText);
var err = '';
$.each(JSON.parse(xhr.responseText) , function(i, item) {
err +='<li>'+item.msg+'</li>';
});
$(".err-area").html(err);
return false;
}
});
}
function deleteUser(user_id){
$.ajax({
url:"/api/user/"+user_id,
type: 'DELETE',
success: function(res) {
window.location.reload();
return false;
},
error:function(xhr, status, error){
console.log(xhr.responseText);
alert("Error deleting");
return false;
}
});
}
</script>
</body>
</html>
All you need is res.render("path to ejs file", {variables...}) to convert the ejs template to HTML response.
app.set('views','./views');
app.set('view engine','ejs');
This part takes care of the rendering HTML.

Connecting to MongoDB using Express

I am having trouble understanding what needs to be done in order to connect to MongoDB so i can insert an Object into the database. I am new to using Express as well as MongoDB and don't have a full grasp on the both of them yet.
My app.js which was created using the standard Express setup is as follows.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ex_session = require('express-session');
var dateformat = require('dateformat');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/contacts'
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
My index.js is as follows and what i would like to happen is when a post request is made from /mailer, a connection is made to the MongoDB in order to set up for an insert.
var express = require('express');
var router = express.Router();
var url = 'mongodb://localhost:27017/contacts';
var contacts;
/* GET home page. */
var start = function(req, res, next){
console.log("Starting!");
res.render('mailer',{});
}
router.get('/', start);
router.get('/mailer', start);
/* Post mailer Page insert into database*/
router.post('/mailer', function(req, res, next){
res.render('thanks');
console.log("Welcome to the Thank You Page");
MongoClient.connect(url, function(err, db){
if(err == NULL){
console.log("Connected to database");
// parse the body of the page and set up object to send to the
// database
}
});
});
router.get('/contact', function(req, res){
res.render('contact', {});
})
module.exports = router;
*for express ,
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DB_USERNAME+':'+DB_PASSWORD+'#'+DB_HOST+':'DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server for express
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DB_HOST+':'+DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
Your code is super mess,I can show your my configuration and u can refer to.
db.js
import mongoose from 'mongoose';
export default function connectDB() {
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/contacts');
mongoose.connection.once('open', function () {
console.log('mongodb connected.');
});
};
app.js
import connectDB from "db.js";
connectDB();
user.model.js
import mongoose from 'mongoose';
const schema = mongoose.Schema({
email: {type: String, required: true},
mobile: {type: String},
password: {type: String, required: true},
});
const User = mongoose.model('User', schema, 'user');
export default User;
then in your router file u can call User.find() or User.update or ...

Is there a way to include jade file directly in html file?

How can I combine a node.js website that its frontend is based on html with another node.js website that its frontend is based on jade template engine? I am using Express framework.
On the frontend there are four files: index.html, index2.html, chat1.html, chat2.html, which are located in the public folder. The blog website that I want to add to this website has only jade template engine, which are located in the views folder.
The index.html (which is in public folder) is the entry point to the home page of the website. When from index.html I refer to index3.jade, which is the Home page of the second app, i.e., blog jade app, Chrome browser states: "404 Not Found". However, I can go to the other two pages of the blog jade website, i.e., Add Post and Add Category. It is only the Home page of the blog jade app that is not being displayed.
So, I am not able to see only the Home page of the blog jade app, which starts at the root directory. Both the html app and the blog jade app start at the root directory. I was able to make the blog jade app to be displayed at the root directory, but then I could not see the html app, which also starts at the root directory.
Here is how I referred to each file from index.html front page:
`<li>gallery</li>`
`<li>chat</li>`
`<li>blog</li>`
Is there a way to have the home page of the blog jade app to be displayed at a directory other than the root directory?
Here is the related app.js code:
// Gallery HTML Code
var routes = require('./');
app.get('/public/index.html');
// Blog Code
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');
var routes = require('./');
var routes = require('./routes/index3');
var posts = require('./routes/posts');
var categories = require('./routes/categories');
var app = express();
app.locals.moment = require('moment');
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect-Flash from Express-Messages
app.use(flash());
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use('/index3', routes);
app.use('/posts', posts);
app.use('/categories', categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is the related code from index3.js in the routes folder:
router.get('index3', function(req, res, next) {
var db = req.db;
var posts = db.get('posts');
posts.find({}, {}, function(err, posts) {
res.render('index3', { posts: posts });
});
});
module.exports = router;
Here is the related code from index.js in the routes folder:
router.get('/', function(req, res, next) {
res.render('public/index.html');
});
module.exports = router;