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');
};
Related
I'm trying to make a login form where it fetches from another website, although, it keeps erroring with Error: Failed to Fetch
I don't really notice anything wrong with the code, but maybe its something related to CORS
Here is my code (HTML, CSS, JavaScript)
// Values: UsernameVal is being tested as "Developer"
// PasswordVal is being tested as "AccessTest"
if (User.value != "") {
if (Password.value != "") {
setFormMessage(loginForm, "info", "Checking account credentials..") // Set form message is just a basic function to set a login status message
var UsernameVal = User.value
var PasswordVal = Password.value
function a(data) {
console.log(data)
if (data.success == true) {
setFormMessage(loginForm, "success", "Logging in..")
} else {
setFormMessage(loginForm, "error", "Invalid username or password")
}
}
try {
console.log(`https://mysite.repl.co/check?username=${UsernameVal}&password=${PasswordVal}/`)
fetch(`https://mysite.repl.co/check?username=${UsernameVal}&password=${PasswordVal}/`, {
method: 'GET',
headers: {
accept: 'application/json',
},
})
.then(data => {
a(data)
}).catch((error) => {
throw new Error(error)
})
} catch (e) {
throw new Error(`Error setting login form message: ${e}`)
}
} else {
setFormMessage(loginForm, "error", "No password input provided")
}
} else {
setFormMessage(loginForm, "error", "No username input provided")
}
});
This is the code on the other side (nodejs)
const express = require('express');
const app = express();
const router = express.Router();
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const fs = require('fs')
app.post('/user', function(req,res) {
res.set("Access-Control-Allow-Origin", "OriginForGettingData")
const username = req.body.username
const password = req.body.password
res.send(`Added to login (${username}: ${password}}) list`)
const table = require('./values.json').Logins;
table[username] = password;
const fileName = './values.json';
const file = require(fileName);
file.Logins = table;
fs.writeFile(fileName, JSON.stringify(file)).done(function writeJSON(err) {
if (err) return console.log(err);
});
console.log(`Post recieved from ${insert}. New table: ${table}`)
})
app.get('/check', function(req,res){
res.set("Access-Control-Allow-Origin", "OriginForGettingData")
const username = req.param("username")
const password = req.param("password")
const table = require('./values.json').Logins;
res.json({"success": table[username] === password})
})
app.listen(3000, () => {
console.log('server started');
});
/user and /check work fine, its just the fetching that fails
After modifying the CORS for Access-Control-Allow-Origin from OriginForGettingData to *, it allowed the request to go through
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});
});
}
So here I have a big problem: I need to create an array that stores an SQL value, in a json file (the code is below). The thing is, where do I declare the query, or what extra should I add to make it work properly? I have created the function viewMontadora, and it works normally when I run the server, listing all the car makers registered in SQL, with all their info. I'm still not very familiar with node.js.
app.use(express.static(__dirname + '/library'))
app.listen(port, () => {
console.log(`Servidor online em
http://localhost:${port}`)
})
app.get('/', (req, res) => {
res.render('pages/home')
})
app.get('/about', (req, res) => {
function viewMontadora() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM VIEW_PRODUTOS").then(function (recordset) {
res.contentType('application/json');
res.send(JSON.stringify(recordset));
console.log(recordset);
conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
}
return viewMontadora();
})
app.get('/contact', (req, res) => {
res.render('pages/contact')
})
app.post('/contact', (req, res) => {
res.send('Obrigado por entrar em contato conosco, ' + req.body.name + '!Responderemos em breve!')
})
app.post('/client', (req, res) => {
// Lista de Utilizadores
var usersValid = [{
username: 'SELECT [RazaoSocial] FROM [SITE].[dbo].[Clientes]',
email: 'SELECT [Email] FROM [SITE].[dbo].[Clientes]'
}, ];
console.log(usersValid);
var error = [{
id: 1,
ErrorLogin: 'Usuario não identificado'
}];
usersValid.push({
username: req.body.name,
email: req.body.email
});
for (var i = 0; i < usersValid.length; i++) {
if (usersValid[i].username === req.body.name && usersValid[i].email ===
req.body.email) {
var dataClient = [{
nameClient: req.body.name,
emailClient: req.body.email,
imgClient: 'http://lmdsneto.000webhostapp.com/images/user.png'
}]
res.render('pages/client', {
dataClients: dataClient
})
//res.send('Bem vindo, ' + req.body.name + ' Email ' +
req.body.email
} else {
res.send(error);
}
}
});
On a high level you need to receive a email and password from the client Eg. Browser, then you need to confirm if that username and password exist in your db. if then do then you can say that they are a valid user.
So aside from security concerns about storing passwords in plain text you should be able to just simply do this: (Obviously just change any values for the user id that you need)
app.post('/client', (req, res) => {
// place userInfo into an object
var userInfo = {
email: req.body.name,
password: req.body.password
};
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM FROM [SITE].[dbo].[Clientes] WHERE email = " +
userInfo.email +
" AND password = " +
userInfo.password).then(function (selectedUser) {
// if we have one selected user we know it is valid
if (selectedUser.length === 1) {
// user is valid
} else {
// user is not valid
}
});
}).catch(function (err) {
console.log(err);
});
});
if (token_count == 1) {
var user_name = rows[0].user_name;
next();
} else {
data = {
message :"Invalid Token"
}
res.send(data);
}
I need to pass user_name as a parameter from next(), the function which it gets called is as bellow,
router.post('/dashboard', function (req, res) {
// user_name must be fetched here
console.log("middleware next")
});
You can add data to the req object
if (token_count == 1) {
var user_name = rows[0].user_name;
req.user_name = user_name;
next();
}else{
data = {
message :"Invalid Token"
}
res.send(data);
}
router.post('/dashboard', function (req, res) {
// user_name must be fetched here
console.log(req.user_name)
});
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)
}
},
})