I'm trying to insert data into my database using a POST request. Data is being sent to my server but when I try to INSERT it into my database it doesn't do anything. Even the console.log in the query is being sent to the console. The req.file is showing the right info as well.
var express = require('express');
var app = express();
var multer = require('multer');
var cors = require('cors');
var bodyParser = require('body-parser');
const port = 8000;
const Pool = require('pg').Pool
const pool = new Pool({
user: 'me',
host: 'localhost',
database: 'api',
password: 'password',
port: 5432,
})
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname)
}
})
var upload = multer({ storage: storage });
app.post('/upload', upload.single('file'), function(req, res) {
message: "Error! in image upload."
if (!req.file) {
console.log("No file recieved");
message = "Error! in image upload."
console.log("status: danger");
} else {
console.log('file recieved');
console.log(req.file);
var query = pool.query('INSERT INTO file (name, type, size) VALUES ($1, $2, $3)', [req.file.filename , req.file.mimetype, req.file.size], function(err, result) {
console.log('inserted data')
});
message = "Successfully uploaded";
console.log("status: success");
}
})
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
Related
please help me solve the issue it's very important I have included the code of my index.js, routes.js, and db.js files I have even added an image of my error.
index.js code
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', 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);
//Listening on port 3000
// app.listen(3000, () => {
// console.log("port 3000")
// })
app.listen(port, () => console.log(`listening on http://${process.env.HOST}:${port}`));
routes.js code
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;
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 code
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 };
picture of the error
please help me solve the issue it's very important I have included code of my index.js, routes.js and db.js files I have even added an an image of my error.
Looks like you're missing const { con } = require("./config/db") (assuming it's in the same directory) in your routes.js file.
Try defining con in your routes.js file:
const {
con,
sessionStore
} = require('./config/db');
exports.new = function(req, res){
message = '';
if(req.method == "POST"){
const post = req.body;
// Rest of the code...
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
Just 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.
I'm using node and express to send email through html page.
Following is my app:
`const express = require('express');
const path = require('path');
const nodeMailer = require('nodemailer');
const bodyPaser = require('body-parser');
const app = express()
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.set('view engine', 'html');
app.use(express.static('public'));
app.use(bodyPaser.urlencoded({ extended: true }));
app.use(bodyPaser.json());
var port = 3000;
app.get('/', function (req, res) {
res.render('index.html');
app.locals.layout = false;
});
//internet connectivity check out
function checkInternet(cb) {
require('dns').lookup('google.com', function (err) {
if (err && err.code == "ENOTFOUND") {
cb(false);
} else {
cb(true);
}
})
}
app.post('/', (req, res) => {
const output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul>
<li>Name:${req.body.name}</li>
<li>Email:${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
// create reusable transporter object using the default SMTP transport
let transporter = nodeMailer.createTransport({
host: "mail.example.com",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: 'contact#example.com', // generated ethereal user
pass: 'Y#$972200424' // generated ethereal password
},
tls: {
rejectUnauthorized: false
}
});
// send mail with defined transport object
let mailOptions = {
from: `${req.body.email}`, // sender address
to: "contact#example.com", // list of receivers
subject: "Customer Message", // Subject line
text: `SenderName: ${req.body.name}, --Message: ${req.body.message}`, // plain text body
html: output // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodeMailer.getTestMessageUrl(info));
if (info.messageId) {
res.redirect('back');
res.send(true);
}
});
});
app.listen(3000, () => console.log('server is running at port 3000'));`
the thing is it sends email and works fine on localhost:3000 but the same does NOT work on index.html page.
how can I have it to send email on the html page?
Simply move html files to the public directory below
You must be change
app.use(express.static('public'));
to
app.use(express.static(`${__dirname}/public`));
also change:
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
to
app.get('/', function (req, res) {
res.sendFile(path.join(`${__dirname}/public/index.html`));
});
Follow the order of the lines:
app.use(express.static(`${__dirname}/public`));
app.get('/', function (req, res) {
res.sendFile(path.join(`${__dirname}/public/index.html`));
});
Also you can use template engine pug. see this doc:
Using template engines with Express
i am using nodejs with multer to create a Image file upload to my shopDB mongo DB
when i upload a image file and post the data from the form ... everything in the form gets saved in the DB but the imagename is showing null and the image is not getting stored in the file path
i am getting no error in the console while saving the form data
and the app is running fine except for the file upload
this is how the upload is inside the form
<div id="img">
<input type='file' name="uploadpostfile">
</div>
THIS IS MY APP.JS
const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require("path");
const Post = require('./models/postup');
const uploadPath = path.join("public", Post.postImgPath);
const bodyParser = require("body-parser");
const imageMimeTypes = ["images/jpeg", "images/png", "images/gif"]
const upload = multer({
dest: uploadPath,
fileFilter: (req, file, callback) => {
callback(null, imageMimeTypes.includes(file.mimetype) )
}
})
const request = require("request");
const ejs = require("ejs");
require('./models/postup')
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/shopDB");
const db = mongoose.connection
db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to Mongoose', {useNewUrlParser: true}, { useUnifiedTopology: true}))
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
app.post("/npost", multer(upload).single("uploadpostfile"), (req, res) => {
let fileName = req.file != null ? req.file.filename : null
let post = new Post({
tag: req.body.taginput,
title: req.body.posttitle,
link: req.body.extlink,
text1: req.body.textsmall,
text2: req.body.textmedium,
text3: req.body.textlarge,
imgname: fileName
})
post.save((err, doc) => {
if (!err)
res.redirect('editor');
else {
console.log('Error' +err )
}
})
})
app.get('/', (req, res) => {
res.render('index');
});
app.get('/editor', (req, res) => {
res.render('editor');
});
app.listen(3000, function(){
console.log("Server on 3000");
})
You can try after saving a post, update the image.
const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require("path");
const Post = require('./models/postup');
const uploadPath = path.join("public", Post.postImgPath);
const bodyParser = require("body-parser");
const imageMimeTypes = ["images/jpeg", "images/png", "images/gif"]
const upload = multer({
dest: uploadPath,
fileFilter: (req, file, callback) => {
callback(null, imageMimeTypes.includes(file.mimetype) )
}
})
const request = require("request");
const ejs = require("ejs");
require('./models/postup')
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/shopDB");
const db = mongoose.connection
db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to Mongoose', {useNewUrlParser: true}, { useUnifiedTopology: true}))
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
app.post("/npost", multer(upload).single("uploadpostfile"), (req, res) => {
let fileName = req.file != null ? req.file.filename : null
let post = new Post({
tag: req.body.taginput,
title: req.body.posttitle,
link: req.body.extlink,
text1: req.body.textsmall,
text2: req.body.textmedium,
text3: req.body.textlarge,
})
post.save((err, doc) => {
if (!err)
res.redirect('editor');
else {
imgname = fileName;
post.findOneAndUpdate({ _id: doc._id }, { $set: imgname }, {
upsert: true, new: true }).exec((error, post) => {
if(error) {
res.status(500).json({ message:'internal server error' });
} else {
res.status(200).json({message:'image upload sucessfully.})
console.log('Error' +err )
}
})
})
app.get('/', (req, res) => {
res.render('index');
});
app.get('/editor', (req, res) => {
res.render('editor');
});
app.listen(3000, function(){
console.log("Server on 3000");
})
I'm learing ExpressJS, and so far I did the user registration part but when I want to redirect to the home page after finishing the registration, it's not
showing the json after clicking on Submit button. May I know how I could do it.
Database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:'reciepeapp'
});
module.exports = con
the ORM
const con = require('./db')
The ORM
const orm = {
insertOne: function (values, cb) {
const sqlQuery = "INSERT INTO authentication(username,password) VALUES ?";
con.query(sqlQuery, [values],function (err, data) {
if (err) {
console.log(err)
cb(err, null);
} else {
cb(null, data);
}
});
},
}
module.exports = orm;
The route.js
Here I insert the data obtained during registration (register index html) into a database. It's working well but I want to redirect to home page.
const express = require('express');
const app = express()
const router = express.Router()
const bcrypt = require('bcrypt');
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const orm = require('../models/orm')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register',(req,res)=>
res.render('register')
)
router.post("/register", async (req, res) =>{
try {
const hashedPassword = await bcrypt.hash(req.body.password,10)
values = { username: req.body.name,
password:hashedPassword }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
values = { username: values.username,
password: values.password }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
**return res.send({
username: values.username,
password: values.password
});**
});
});
}
catch {
}
});
module.exports = router
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
To do this you need to use express's redirect method.
Example:
var express = require('express');
var app = express();
const urlBase = 'localhost:3000/'
app.post('/', function(req, res) {
const redirectUrl = "index.html"
res.redirect(urlBase + redirectUrl);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Docs: Express 4.x Docs