Please help me solve the error. I have attached my index.js code routes.js code and db.js code and the error description. I've been trying hard to solve the error.
index.js
const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const session = require('express-session');
const auth = require('./routes/auth');
const {
con,
sessionStore
} = require('./config/db');
const fs = require('fs');
require('dotenv').config({
path: path.join(__dirname, '.env')
});
const port = process.env.PORT || 3000;
// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
//static files
app.use(express.static('public'))
app.use('/css' , express.static(__dirname + 'public/css'))
app.use('/imgs' , express.static(__dirname + 'public/imgs'))
var sess = {
secret: 'keyboard cat',
store: sessionStore,
cookie: {
httpOnly: false,
},
resave: false,
saveUninitialized: false
}
app.use(session(sess));
app.use(fileUpload());
//set views
app.set('view engine' , 'ejs');
app.set('views', path.join(__dirname, 'views'))
//
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('/', (req,res) =>{
res.render('index22')
})
app.get('/login', (req, res) => {
res.render('login');
});
let s;
const loginRequired = (req, res, next) => {
if (req.session.username) {
s = req.session;
next();
} else {
res.redirect('/auth/login');
}
}
// app.get('/new', (req, res) => {
// res.render('new');
// });
// app.get('/show', (req, res) => {
// res.render('show');
// });
// app.get('/', loginRequired, (req, res) => {
// res.redirect('/new');
// });
// app.get('/', loginRequired, (req, res) => {
// res.redirect('/show');
// });
app.get('/new', loginRequired, routes.new);//call for main index page
app.post('/new', loginRequired, routes.new);//call for signup post
app.get('/show', loginRequired, routes.show);
app.use('/auth', auth);
app.listen(port, () => console.log(`listening on http://${process.env.HOST}:${port}`));
routes.js
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.uploads;
const 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) {
if (err)
return res.status(500).send(err);
const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `img_name` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + image + "','" + description + "')";
const query = con.query(sql, function(err, result) {
res.redirect('show/'+result.insertUsername);
});
});
} 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){
const message = '';
const username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
db.js
const mysql = require('mysql');
const path = require('path');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
require('dotenv').config({ path: path.join(__dirname, '../.env') });
// config for your database
const con = mysql.createConnection({
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
server: process.env.DB_HOST,
database: process.env.DB_NAME,
port: parseInt(process.env.DB_PORT)
});
var sessionStore = new MySQLStore({}/* session store options */, con);
// connect to your database
con.connect((err) => {
if (err) throw err;
console.log("Connected to database");
});
module.exports = { con, sessionStore };
Description of the error:
C:\Users\hp\Desktop\Internship\Nt\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
TypeError: Assignment to constant variable.
at Query.<anonymous> (C:\Users\hp\Desktop\Nt\routes.js:50:12)
at Query.<anonymous> (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
at Query.EofPacket (C:\Users\hp\Desktop\\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
at Protocol._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:38:16)
I guess mainly the error is in the routes.js file Any help will be highly appreciated. Thank you
Please help me solve the error. I have attached my index.js code routes.js code and db.js code and the error description. I've been trying hard to solve the error.
index.js
const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const session = require('express-session');
const auth = require('./routes/auth');
const {
con,
sessionStore
} = require('./config/db');
const fs = require('fs');
require('dotenv').config({
path: path.join(__dirname, '.env')
});
const port = process.env.PORT || 3000;
// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
//static files
app.use(express.static('public'))
app.use('/css' , express.static(__dirname + 'public/css'))
app.use('/imgs' , express.static(__dirname + 'public/imgs'))
var sess = {
secret: 'keyboard cat',
store: sessionStore,
cookie: {
httpOnly: false,
},
resave: false,
saveUninitialized: false
}
app.use(session(sess));
app.use(fileUpload());
//set views
app.set('view engine' , 'ejs');
app.set('views', path.join(__dirname, 'views'))
//
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('/', (req,res) =>{
res.render('index22')
})
app.get('/login', (req, res) => {
res.render('login');
});
let s;
const loginRequired = (req, res, next) => {
if (req.session.username) {
s = req.session;
next();
} else {
res.redirect('/auth/login');
}
}
// app.get('/new', (req, res) => {
// res.render('new');
// });
// app.get('/show', (req, res) => {
// res.render('show');
// });
// app.get('/', loginRequired, (req, res) => {
// res.redirect('/new');
// });
// app.get('/', loginRequired, (req, res) => {
// res.redirect('/show');
// });
app.get('/new', loginRequired, routes.new);//call for main index page
app.post('/new', loginRequired, routes.new);//call for signup post
app.get('/show', loginRequired, routes.show);
app.use('/auth', auth);
app.listen(port, () => console.log(`listening on http://${process.env.HOST}:${port}`));
routes.js
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.uploads;
const 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) {
if (err)
return res.status(500).send(err);
const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `img_name` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + image + "','" + description + "')";
const query = con.query(sql, function(err, result) {
res.redirect('show/'+result.insertUsername);
});
});
} 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){
const message = '';
const username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
db.js
const mysql = require('mysql');
const path = require('path');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
require('dotenv').config({ path: path.join(__dirname, '../.env') });
// config for your database
const con = mysql.createConnection({
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
server: process.env.DB_HOST,
database: process.env.DB_NAME,
port: parseInt(process.env.DB_PORT)
});
var sessionStore = new MySQLStore({}/* session store options */, con);
// connect to your database
con.connect((err) => {
if (err) throw err;
console.log("Connected to database");
});
module.exports = { con, sessionStore };
Description of the error:
C:\Users\hp\Desktop\Internship\Nt\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
TypeError: Assignment to constant variable.
at Query.<anonymous> (C:\Users\hp\Desktop\Nt\routes.js:50:12)
at Query.<anonymous> (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
at Query.EofPacket (C:\Users\hp\Desktop\\Nt\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
at Protocol._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\hp\Desktop\Nt\node_modules\mysql\lib\protocol\Protocol.js:38:16)
I guess mainly the error is in the routes.js file Any help will be highly appreciated. Thank you
Share Improve this question asked Nov 28, 2020 at 3:32 user14398337user143983373 Answers
Reset to default 9Just update const
to let
in the show
function:
exports.show = function(req, res){
let message = '';
const username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
Or given you don't really need to reassign it, just create the variable inside the body if the if
statement:
exports.show = function(req, res){
const username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
const message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
Hopefully that helps!
Once you declare a const
you cannot reassign it. Check out the MDN docs for more information.
This won't work
const message = ""
message = "show not found!";
This will
let message = ""
message = "show not found!"
I had a similar issue with connect-mongo
. Double-check with the express-mysql-session
latest docs and check if you're importing packages you already required accidentally. Sometimes, ``IDEs like Visual Studio Code
does this. It was importing const{express-session}
by the IDE and assigning it to mongostore.