My code works fine if don't redirect my show.ejs file then this error doesn't show up but when I try to redirect it to places.ejs it shows this error I don't know where I'm going wrong please help me solve this issue.I'm attaching herewith my error log , a part of the index.js code and routes.js code Thank you
error
ReferenceError: C:\Users\hp\Desktop\Nt\views\show.ejs:38
36| <div class="card" style="width: 18rem;">
37|
>> 38| <img src="http://localhost:3000/imgs/uploads/<%=data[0].images%>" class="card-img-top responsive" alt="...">
39| <div class="card-body">
40| <h5 class="card-title"><%=data[0].title%></h5>
41| <p class="card-text"><%=data[0].description%></p>
data is not defined
part of my index.js code
app.get('/new', loginRequired, routes.new);
app.post('/', loginRequired, routes.new);
app.get('/show/:username', loginRequired, routes.show);
app.get('/places', loginRequired, routes.places);
routes.js code:
const {
con,
sessionStore
} = require('./config/db');
const { route } = require('./routes/auth');
exports.new = function(req, res){
message = '';
if(req.method == "POST"){
const post = req.body;
const username= post.username;
const title= post.title;
const state= post.state;
const category= post.category;
const description= post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploaded_image;
var img_name=file.name;
if(file.mimetype == "image/jpeg" ||file.mimetype == "image/png"||file.mimetype == "image/gif" ){
file.mv('public/imgs/uploads/'+file.name, function(err) {
var sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES (?,?,?,?,?,?)";
var query = con.query(sql, [username, title, state, category, img_name, description], function(err) {
console.log(err)
if (!err) {
res.redirect('show/' + username);
}
else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs',{message: message});
}
});
});
}
}
else {
res.render('new');
}
};
exports.show = function(req, res){
let message = '';
var username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
console.log(err)
if(result.length <= 0){
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
}else{
res.redirect('/places');
}
});
res.render('show')
};
exports.places=function (req,res,result){
let message = '';
var username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
console.log(err)
if(result.length <= 0)
console.log(err)
message = "places not found!";
res.render('places.ejs',{data:result, message: message});
});
}
Related
I'm trying to open places.ejs file by clicking the submit button on show.js page, just like the show.ejs page opens on clicking the submit button on new.ejs file, but a reference error is occurring. Please help me fix the error. I'm attaching herewith my routes.js code and a part of my index.js code Any help would be highly appreciable. Thank you
Here's my routes.js code
const { con, sessionStore } = require('./config/db');
exports.new = function (req, res) {
message = '';
if (req.method == "POST") {
const post = req.body;
const username = post.username;
const title = post.title;
const state = post.state;
const category = post.category;
const description = post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploaded_image;
var img_name = file.name;
if (file.mimetype == "image/jpeg" || file.mimetype == "image/png" || file.mimetype == "image/gif") {
file.mv('public/imgs/uploads/' + file.name, function (err) {
var sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES (?,?,?,?,?,?)";
var query = con.query(sql, [username, title, state, category, img_name, description], function (err) {
console.log(err)
if (!err) {
res.redirect('show/' + username + '/' + category);
}
else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs', { message: message });
}
});
});
}
}
else {
res.render('new');
}
};
exports.show = function (req, res) {
let message = '';
con.query('SELECT * FROM nt_data WHERE username=? AND category=?', [req.params.username, req.params.category], (err, result) => {
console.log(err)
if (result.length <= 0) {
message = "show not found!";
res.render('show.ejs', { data: result, message: message });
}
else {
res.redirect('places/' + username);
}
});
res.render('show');
};
here's a part of my index.js code
app.get('/new', loginRequired, routes.new);
app.post('/', loginRequired, routes.new);
app.get('/show/:username/:category', loginRequired, routes.show);
app.post('/', loginRequired, routes.show);
app.get('/places/:username', loginRequired, routes.show);
error
ReferenceError: data is not defined
ReferenceError: username is not defined
In show function, you need to get username like this:
req.params.username
And for data I don't see where do you reference it, in witch line to do get an error?
exports.show = function (req, res) {
let message = '';
con.query('SELECT * FROM nt_data WHERE username=? AND category=?', [req.params.username, req.params.category], (err, result) => {
console.log(err)
if (result.length <= 0) {
message = "show not found!";
res.render('show.ejs', { data: result, message: message });
}
else {
res.redirect('places/' + req.params.username); // Change here
}
});
res.render('show');
};
I'm a beginner in NodeJS and I've tried to make an authentication form using NodeJS + express. I want to make a validation for my password (when "confirmpassword" is different than "password" it should return nothing. Unfortunately, I keep getting "data and salt arguments required". I tried in different ways, to put some conditions, but I keep getting this error. Any ideas how I should make it work?
Here is the file user.js:
const pool = require('./pool');
const bcrypt = require('bcrypt');
function User() {};
User.prototype = {
find : function(user = null, callback)
{
if(user) {
var field = Number.isInteger(user) ? 'id' : 'username';
}
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result) {
if(err)
throw err
if(result.length) {
callback(result[0]);
}else {
callback(null);
}
});
},
create : function(body, callback)
{
var pwd = body.password;
var cpwd = body.confirmpassword;
// here i hash the pass
body.password = bcrypt.hashSync(pwd,10);
body.confirmpassword = bcrypt.hashSync(cpwd, 10);
if (body.password != body.confirmpassword){
callback(null);
}
else {
var bind = [];
for(prop in body){
bind.push(body[prop]);
}
let sql = `INSERT INTO users(username, fullname, password) VALUES (?, ?, ?)`;
pool.query(sql, bind, function(err, result) {
if(err) throw err;
callback(result.insertId);
});
}
},
login : function(username, password, callback)
{
this.find(username, function(user) {
if(user) {
if(bcrypt.compareSync(password, user.password)) {
callback(user);
return;
}
}
callback(null);
});
}
}
module.exports = User;
And the file pages.js:
const express = require('express');
const User = require('../core/user');
const router = express.Router();
const user = new User();
router.get('/', (req, res, next) => {
let user = req.session.user;
if(user) {
res.redirect('/home');
return;
}
res.render('index', {title:"My application"});
})
router.get('/home', (req, res, next) => {
let user = req.session.user;
if(user) {
res.render('home', {opp:req.session.opp, name:user.fullname});
return;
}
res.redirect('/');
});
router.post('/login', (req, res, next) => {
user.login(req.body.username, req.body.password, function(result) {
if(result) {
req.session.user = result;
req.session.opp = 1;
res.redirect('/home');
}else {
res.send('Username/Password incorrect!');
}
})
});
router.post('/register', (req, res, next) => {
let userInput = {
username: req.body.username,
fullname: req.body.fullname,
password: req.body.password
};
user.create(userInput, function(lastId) {
if(lastId) {
user.find(lastId, function(result) {
req.session.user = result;
req.session.opp = 1;
res.redirect('/home');
});
}else {
console.log('Error creating a new user ...');
}
});
});
router.get('/logout', (req, res, next) => {
if(req.session.user) {
req.session.destroy(function() {
res.redirect('/');
});
}
});
module.exports = router;
In userInput, you are not passing confirmpassword property.
let userInput = {
username: req.body.username,
fullname: req.body.fullname,
password: req.body.password
};
In create method, you are accessing it.
var cpwd = body.confirmpassword;
cpwd is null, and that's the reason for the error.
body.confirmpassword = bcrypt.hashSync(cpwd, 10);//**cpwd is null**
As per the docs, data is required argument and this cannot be null.
hashSync(data, salt)
data - [REQUIRED] - the data to be encrypted.
salt - [REQUIRED] - the salt to be used to hash the password.
how can i make a post request from a router, it works on the "/" pages but not working on the "/forget" page. when i replace "/forget" page to "/" pages it works fine but when the post method is from "/forget" it give error. here is my code
please help look at it
thanks in advance
this is my "/" pages it works fine here
var express = require('express');
var router = express.Router();
router.post('/activate', function(req, res) {
var register = {
Email: req.body.emial,
Password: req.body.password,
C_password: req.body.c_password
}
var newUser = {
Referer_mail : req.body.ref_email,
Name : req.body.name,
Country : req.body.country,
Phone: req.body.phone,
Email: req.body.emial,
Wallet : 0 ,
Invest : 0 ,
Interest : 0 ,
Income : 0,
referal : 0
}
if (register.Password === register.C_password){
firebase.registerWithEmail(register.Email, register.Password, newUser, function(err, result){
if (err){
console.log(err);
Message = err.message;
}else {
// send emial verification
firebase.sendVerificationEmail(result.token, function(err, result){
if (err){
console.log(err);
Message = err.message;
}else {
console.log(result);
}
});
// save name in data base
firebase.database().ref("Profile").child(result.user.id).set({newUser}, function (err, result){
if (err){
console.log(err);
Message = err.message;
} else {
console.log(result);
}
})
console.log(result);
}
});
res.render('pages/activate', {
value : Message
});
} else {
console.log("password and confrim password not equal");
res.render('pages/index', {
value : " Your Password and Confrim Password are not equal"
});
}
});
while this is my "/forget" pages give error
var express = require('express');
var router = express.Router();
router.post('/activate', function(req, res) {
res.render('pages/activate', {
value : Message
});
});
please help me find time and look at it,
thanks in advance
In my project the admins have the ability to upload MP3 files and submit parameters to it like song name.
I decided using multer middleware for handling multipart/form-data.
My problem is req.body.gender returns always undefined, because I have to use it inside the uploadSong listener. I want to upload the song when the gender is zero.
index.ejs
<form method="post" action="/acp" role="publish" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="song" id="song" accept="audio/mpeg">
</div>
<input type="checkbox" name="gender" checked data-toggle="toggle" data-on="Male" data-off="Female">
</form>
app.js
var uploadSong = upload.single('song');
app.post('/acp', isLoggedIn, function (req, res) {
console.log(req.body.gender); // returns "undefined"
if(req.body.gender == 0) { // returns "undefined"
uploadSong(req, res, function (err) {
if (err) {
res.send('uploaded');
return;
}
res.redirect('/');
});
}
});
(A) Not possible with multer.
(B) Use busboy. It uses streams to parse the form data and so you can get form elements values before the file upload and the fields are made available as events.
(C) Another solution (if you prefer using multer) is to use multer but add a header to send the value of the parameter to check before file upload. Headers are available as soon as the request reaches the server.
by using multer form-data parser you can parse form and access req.body before multer starts just register this app middle-ware:
import * as multer from "multer";
// parse form-data
app.use(multer().any());
This is my sample code, it is woking fine, if you need further explanation please let me know. hope helpful.
var Hotel = require('../models/hotel');
var path = require('path');
var multer = require('multer');
var uplodedImages = [];
var storageHotelGallery = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/hotelGallery');
},
filename: function (req, file, cb) {
console.log(req.body);
var newFileName = Date.now() + path.extname(file.originalname);
req.newFileName = newFileName;
cb(null, newFileName);
uplodedImages.push(newFileName);
}
});
var uploadHotelGallery = multer({ storage: storageHotelGallery}).fields([{ name: 'imgArr', maxCount: 8 }]);
module.exports = function(router) {
// ADD HOTEL BASIC DATA TO CREATE HOTEL OBJECT
router.post('/createHotelStep1', function(req, res) {
if( req.body.name == null || req.body.name == '' ) {
res.json({ success: false, message: "Hotel name required" });
res.end();
}
else if( req.body.addressline1 == null || req.body.addressline1 == '' ) {
res.json({ success: false, message: "Address line 1 is required" });
res.end();
}
else if( req.body.city == null || req.body.city == '') {
res.json({ success: false, message: "City is required" });
res.end();
}
else {
var hotel = new Hotel();
hotel.name = req.body.name;
hotel.addressline1 = req.body.addressline1;
hotel.addressline2 = req.body.addressline2;
hotel.phone = req.body.phone;
hotel.city = req.body.city;
hotel.email = req.body.email;
hotel.save(function(err) {
if (err) {
res.json({ success: false, message: "Unable to Complete Hotel Step 1" });
} else {
res.json({ success: true, message: 'Create Hotel Step 1 Complete', _id : hotel._id });
}
});
}
});
router.post('/createHotelGallery', function (req, res, next) {
uplodedImages = [];
uploadHotelGallery(req, res, function(err) {
if(err) {
res.json({ success: false, message: 'Could not upload images'});
res.end();
}
else {
Hotel.findOne({ _id:req.body._id }).populate('users').exec(function (err, hotel) {
if (err) {
res.json({ success: false, message: 'Could not save uploaded images to database'});
res.end();
}
else {
for(var x=0; x<uplodedImages.length; x++)
hotel.images.push(uplodedImages[x]);
hotel.save();
res.json({ success: true, message: 'Gallery image uploaded' });
res.end();
}
});
}
});
});
return router;
}
This is my sample code, it is woking fine
const upload = multer({
storage,
fileFilter(req, file, cb) {
if(req.body.name===''){
return cb(new Error('Invalid name'), false)
}
const extname = path.extname(file.originalname).toLowerCase() === '.gz'
const mimetype = file.mimetype === 'application/x-gzip'
if (mimetype && extname) {
return cb(null, true)
} else {
return cb(new Error('Invalid mime type'), false)
}
},
})
The error prevents my webpage from being rendered. As mentioned in the title, the error lies in styles.css, when I take this file out, I do not get any errors.
styles.css is included in a separate headers.ejs file which is added in all pages, but there is only one route for which the error is shown(/cats/new). I put up some some logs around my routes and it seems when I enter /cats/new/, I am automatically redirected to a new route (get /cats/:id). I am wondering if this is the cause of the error?
I have attached my routes and the full error message below:
routes:
var express = require('express');
var router = express.Router();
var User = require('../models/user.js');
var Cat = require('../models/cat.js');
var Comment = require('../models/comment.js');
//middleware
function isAuthenticated(req,res,next) {
req.isAuthenticated() ? next() : res.redirect('/login');
}
router.get("/", function(req,res) {
res.redirect("cats");
});
router.get('/cats', function(req,res) {
Cat.find({}, function(err, cats) {
if (err) {
console.log(err);
} else {
res.render('cats', {cats: cats});
}
});
});
router.get('/cats/new', isAuthenticated, function(req,res) {
console.log('went to /cats/new');
res.render('new', {user: req.user});
});
router.post('/cats', isAuthenticated, function(req,res) {
console.log('went to post /cats');
var name = req.body.name;
var image = req.body.url;
var owner = req.user.username
var description = req.body.description;
cat = new Cat({
name: name,
image: image,
owner: owner,
description: description
});
cat.save();
User.findById(req.user._id, function(err, user) {
if (err) {
console.log(err);
} else {
user.cats.push(cat);
user.save();
}
})
res.redirect('cats');
});
router.get('/cats/:id', function(req,res) {
var id = req.params.id;
Cat.findById(id).populate('comments').exec(function(err, cat) {
if (err) {
console.log('entering get /cats/:id');
console.log(err);
} else {
console.log('no errror yet');
console.log(cat.comments);
res.render('show', {cat:cat});
}
});
});
router.post('/cats/:id', isAuthenticated, function(req,res) {
console.log(isAuthenticated);
var id = req.params.id;
Cat.findById(id, function(err, cat) {
console.log('findById running');
if (err) {
console.log(err);
console.log('err finding cat');
res.redirect('/cats');
} else {
console.log('before Comment.create');
Comment.create(req.body.comment, function(err, comment) {
console.log('after Comment.create');
if (err) {
console.log(err);
} else {
console.log('right after 2nd else');
comment.author.id = req.user._id;
console.log(req.user._id);
console.log(req.user.username);
comment.author.username = req.user.username;
comment.cat = id;
comment.save();
console.log('after saving comment');
cat.comments.push(comment);
cat.save();
console.log('saved cat');
User.findById(req.user._id, function(err, user) {
if (err) {
console.log(err);
} else {
user.comments.push(comment);
user.save();
console.log('saved user');
}
});
console.log(comment);
res.redirect("/cats/" + cat._id);
}
});
}
});
});
router.get('/cats/:id/edit', function(req,res) {
var id = req.params.id;
Cat.findById(id, function(err, cat) {
if (err) {
console.log(err);
} else {
res.render('edit.ejs', {cat:cat});
}
});
});
router.put('/cats/:id', function(req,res) {
console.log('beginning /cat/:id');
Cat.findByIdAndUpdate(
req.params.id, req.body.cat, function(err, updatedCat) {
if (err) {
console.log(err);
} else {
console.log('------------ req.body.cat');
console.log(req.body.cat);
console.log('------------ updated cat');
console.log('updated cat');
res.redirect('/cat/' + req.params.id);
console.log('not redirecting?');
}
});
router.delete('/cats/:id',isAuthenticated, function(req,res) {
var id = req.params.id;
console.log('YOU ARE TRYING TO DESTROY A CAT!');
Cat.findByIdAndRemove(id, function(err) {
if (err) {
console.log(err);
res.redirect('/user');
} else {
res.redirect('/user');
}
});
})
});
module.exports = router;
Error:
entering get /cats/:id
{ [CastError: Cast to ObjectId failed for value "styles.css" at path "_id"]
message: 'Cast to ObjectId failed for value "styles.css" at path "_id"',
name: 'CastError',
kind: 'ObjectId',
value: 'styles.css',
path: '_id',
reason: undefined }
It seems you’re including styles.css using a relative path in your template.
So when you navigate to /cats/:id, it tries to load /cats/styles.css.
In order to avoid that, you have to use an absolute path (e.g.: /styles.css or /public/styles.css – I’d recommend serving static files from a dedicated base path).
Go to
<head>
and change
<link rel="stylesheet" href="style.css">
to
<link rel="stylesheet" href="/style.css">