I am using it with node and mysql with angular 5.
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './assets/images/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
const fileFilter = (req, file, cb)=>{
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
cb(null, true);
}
else{
cb(null, false);
}
};
upload = multer({
storage: storage,
limits:{
filesize : 1024 * 1024 * 5
},
fileFilter : fileFilter
});
const app = express();
//DATABASE CONNECTION
const connection = mysql.createConnection({
host: 'localhost',
user:'root',
password: 'root',
database: 'inpblog',
port: 8889
});
// ALLOW CROSS ORIGIN
const corsOptions = {
origin: 'http://localhost:4200',
origin1: 'http://localhost:4202',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.use('./assets/images', express.static(path.join(__dirname, 'dist', 'upload')));
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
connection.connect(function(error){
if(!!error){
console.log("error - db not connected");
}
else{
console.log("connected");
}
});
Here i define the code to upload a image in mysql database. through postman its upload a image in destination folder with multer middleware but when i upload a image through ng form its showing error in console."image undefined" and submit the "c:/fakepath/image.jgg" in mysql.
Here is the API to insert the post
app.post('/insertPost', upload.single('txt_blog_image'), jsonParser, (req, res) => {
console.log("image: ", req.file); // working fine only with postman
//console.log("rBody: ", req.body.txt_blog_image); // working fine only with Angular
let blogFields = {
post_author : req.body.txt_blog_author,
post_image : req.body.txt_blog_image
};
let sql = 'INSERT INTO insdb SET ?';
let query = connection.query(sql, blogFields, (err,result)=> {
res.send('New Post added...');
});
});
// Get All Post
app.get('/getallposts', (req, res) => {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.listen(4202);
Try this way.
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './assets/images/')
},
filename: function(req, file, callback) {
console.log(file)
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
In your api :
app.post('/getallposts',upload.single("image") , function(req, res) {
let sql = 'SELECT * FROM insdb';
let query = connection.query(sql, (err, results) => {
if(err) throw err;
console.log(results);
res.send(results);
});
})
From Angular side :
let form = new FormData();
form.append('image' , file);
Then console in server side , req.files to check file is coming or not ?
For more information and example please see this link
Related
i am still new in node js, and i am trying to make some backend with file upload/ image upload function that can be stored in sql, i am trying using multer but it cant read my file while testing in postman body. anybody can help me where i do wrong?
here is my controller
const { db } = require('./db');
const bodyParser = require('body-parser');
const getgambar = (req, res) => {
const sqlQuery = "SELECT * FROM gambar";
db.query(sqlQuery, (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
console.log(result);
}
});
};
const addgambar = (req,res) => {
const idimg = req.body.idimg;
const gambar = req.file.gambar;
console.log()
const sqlQuery = "INSERT INTO image (idimg,gambar) VALUE (?,?)";
db.query(sqlQuery, [idimg,gambar], (err, result) => {
if (err) {
res.send({
message: "error",
err
})
} else {
res.send({
message: "YES"
})
}
});
};
module.exports = {
getgambar,
addgambar,
};
here is my route
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const ctrl = require('./gambarctrl');
const storange = multer.diskStorage({
destination: './uploads',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storange: storange
})
router.get('/image/display', ctrl.getgambar)
router.post('/image',upload.single('gambar'), ctrl.addgambar)
module.exports = router;
and here my index
const { db } = require('./db');
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const app = express();
const fileUpload = require('express-fileupload');
const gambarroute = require ('./gambarroute');
const multer = require('multer');
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(gambarroute);
app.listen(3000, () => {
console.log('on port 3000!');
});
i am still quite new in node js and i am still searching for tutorial, i appriciate for the help.
Two problems here...
Multer puts the single uploaded file into req.file so you should use
const gambar = req.file; // no `.gambar`
Assuming your DB column is a BLOB or BINARY type, you need to provide a Buffer.
Since you're storing the images within the DB, you don't need to use DiskStorage. Use MemoryStorage instead which provides a Buffer out-of-the-box
const upload = multer({
storage: multer.memoryStorage(), // watch your spelling
})
Then bind the .buffer property in your query.
db.query(sqlQuery, [idimg, gambar.buffer], (err, result) => {
// ...
});
To respond with the image from Express, use something like this
router.get("/image/display/:id", (req, res, next) => {
db.query(
"SELECT `gambar` FROM `image` WHERE `idimg` = ?",
[req.params.id],
(err, results) => {
if (err) {
return next(err);
}
if (!results.length) {
return res.sendStatus(404);
}
// set the appropriate content type
res.set("Content-Type", "image/jpg");
res.send(results[0].gambar);
}
);
});
and from the frontend...
<img src="http://localhost:3000/image/display/some-id" />
Goal:
I am aiming to teach myself how to use Node JS, MySQL and express.
I'm struggling to understand where to place my code for loading MySQL data into HTML.
Let me show you the whole code.
app.js
var express = require('express');
var mysql = require('mysql');
var dotenv = require('dotenv');
var path = require('path');
var cookieParser = require('cookie-parser');
dotenv.config({path: './.env'});
var app = express();
// Connection to MySQL
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
db.connect(function(error) {
if(error) {
console.log(error);
}
else{
console.log("Connected");
}
});
// Parse URL-Encoded bodies
app.use(express.urlencoded({extended: false}));
// Parse JSON bodies
app.use(express.json());
// Initialize a cookie
app.use(cookieParser());
// View engine to control HTML
app.set('view engine', 'hbs');
// Public dir
var publicDir = path.join(__dirname, './public');
app.use(express.static(publicDir));
// Define routes
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(3000, function() {
console.log("Server is running on port 3000");
});
routes/pages.js
var express = require('express');
var authController = require('../controllers/auth');
var router = express.Router();
// Home
router.get("/", authController.isLoggedIn, function(req,res) {
res.render("index", {
user: req.user
});
});
// Register
router.get("/register", function(req, res) {
res.render("register");
});
// Login
router.get("/login", function(req, res) {
res.render("login");
});
// Profile
router.get('/profile', authController.isLoggedIn, function(req, res) {
if(req.user) {
res.render('profile', {
user: req.user
});
}
else {
res.redirect('login');
}
});
// Forum
router.get('/forums', authController.isLoggedIn, function(req, res) {
if(req.user) {
res.render('forums');
} else {
res.redirect('login');
}
});
// English Division //
// Premier League
router.get('/Leagues/EnglishDivision', authController.isLoggedIn, function(req, res) {
if(req.user) {
res.render('PremierLeague');
} else {
res.redirect('../../login');
}
});
module.exports = router;
routes/auth.js
var express = require('express');
var authController = require('../controllers/auth');
var router = express.Router();
// Register
router.post("/register", authController.register);
// Login
router.post("/login", authController.login);
// Logout
router.get('/logout', authController.logout);
module.exports = router;
controllers/auth.js
var mysql = require('mysql');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var {promisify} = require('util');
// Connection to MySQL
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
// Register function
exports.register = function(req, res) {
console.log(req.body);
var {name, email, password, passwordConfirm} = req.body;
db.query("SELECT email FROM users WHERE email = ?", [email], function(error, result) {
if(error){
console.log(error);
}
if(result.length > 0) {
return res.render('register', {
message: 'That email is already in use'
})
} else if(password !== passwordConfirm) {
return res.render('register', {
message: 'Passwords do not match'
});
}
let hashedPassword = bcrypt.hashSync(password, 8);
console.log(hashedPassword);
// Insert user details into MySQL
db.query('INSERT INTO users set ?', {name: name, email: email, password: hashedPassword, dateJoined: new Date()}, function(error, result) {
if(error) {
console.log(error);
} else {
console.log(result);
return res.render('register', {
message: 'User registered'
});
}
});
});
}
// Login function
exports.login = function(req, res) {
try {
var {email, password} = req.body;
if(!email || !password) {
return res.status(400).render('login', {
message: 'Please provide an email and password'
});
}
db.query('SELECT * FROM users WHERE email = ?', [email], async function(error, result) {
console.log(result);
if(!result.length > 0 || !(await bcrypt.compare(password, result[0].password))) {
res.status(401).render('login', {
message: 'The email or password is incorrect'
});
}
else {
var id = result[0].id;
// Create a token
var token = jwt.sign({id}, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN
});
console.log("The token is " + token);
// Create a cookie
var cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true
}
// Set up a cookie
res.cookie('jwt', token, cookieOptions);
res.status(200).redirect("/");
}
});
} catch (error) {
console.log(error);
}
}
// Check if logged in
exports.isLoggedIn = async function(req, res, next) {
console.log(req.cookies);
if(req.cookies.jwt){
try {
// Verify the token
var decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET);
console.log(decoded);
// Check if user exist
db.query("SELECT id, name, email, password, date_format(datejoined, '%d/%m/%Y') as dateJoined FROM users WHERE id = ?", [decoded.id], function(error, result) {
console.log(result);
// If no result
if(!result) {
return next();
}
req.user = result[0];
return next();
});
}
catch (e) {
console.log(e);
return next();
}
} else{
next();
}
}
// Logout function
exports.logout = async function(req, res) {
res.clearCookie('jwt');
res.status(200).redirect('/');
}
Question
In my .hbs file called PremierLeague I'd like to load MySQL data in HTML format. Where in the code below I need to start?
Desired goal:
This is when the user clicks into view premier league
Foreach record in MySQL I'd like to add a new card for each record. I know how to use HandleBars {{some.data}}.
I just don't get where I code the query?
Does it needs to be in a controller or can it be in in the router.get(...?
Also how do I use {{#foreach}} correctly ?
You don't need any other specific controller, the right place to code the query is actually the route itself.
But before entering the core of your question, let's talk a while about your code.
I can see you are performing connection to database more than once, you could add database dedicated controller, something like:
controllers/db.js
var mysql = require('mysql');
var dotenv = require('dotenv');
dotenv.config({path: './.env'});
// Connection to MySQL
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
function connect(done) {
db.connect(done);
}
module.exports = { db: db, connect: connect };
this let you access to the database instance from every file with just one line:
var db = require('./controllers/db').db;
than you could use the connect function in your app:
app.js
var express = require('express');
var db = require(./controllers/db);
var path = require('path');
var cookieParser = require('cookie-parser');
// set up your server
var app = express();
// Parse URL-Encoded bodies
app.use(express.urlencoded({extended: false}));
// Parse JSON bodies
app.use(express.json());
// Initialize a cookie
app.use(cookieParser());
// View engine to control HTML
app.set('view engine', 'hbs');
// Public dir
var publicDir = path.join(__dirname, './public');
app.use(express.static(publicDir));
// Define routes
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
// finally run your server only if you can connect to the database
db.connect(function(error) {
if(error) return console.log("Error connecting to the database:", error);
app.listen(3000, function() {
console.log("Server is running on port 3000");
});
});
you could also simplify you controllers/auth.js removing database connection stuff and using only the line to require your database controller.
Finally you can code your query:
routes/pages.js
var express = require('express');
var authController = require('../controllers/auth');
var db = require('../controllers/db').db;
var router = express.Router();
// Omissis... other routes
// Premier League
router.get('/Leagues/EnglishDivision', authController.isLoggedIn, function(req, res) {
// a good practice is first to handle possible exit cases to reduce nesting levels
if(! req.user) return res.redirect('../../login');
// this is actually the right place to perform queries
db.query('SELECT ...', [...], function(error, results) {
// once again first possible exit cases
if(error) return res.status(500).end(error.message)
res.render('PremierLeague', { results: results });
});
});
module.exports = router;
Last in your PremierLeague.hbs file you can handle the results in a #foreach directive.
Just pass your data when you render the view
router.get('/Leagues/EnglishDivision', authController.isLoggedIn, function(req, res) {
if(req.user) {
connection.query('SELECT * FROM EnglishDivision',function (err,results) {
if (err) throw err;
res.render('PremierLeague',{data: results});
});
} else {
res.redirect('../../login');
}
});
then in the .hbs file
{{#each data}}
<div class="card">
<h3>{{this.someData}}</h3>
<h2>{{this.someData}}</h2>
</div>
{{/each}}
I am not able to import the mysql connection file from the parent file to another file for making a DB connection.
I can connect to DB if the query is written in same file, if i try to hit the same query in another file then i get "TypeError: connection.query is not a function" error. Not able to access any functions of the connection object.
this is my server.js file:
var express = require('express');
var cors = require('cors');
var mysql = require('mysql');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection = mysql.createConnection(config);
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
module.exports= connection;
This is my api.js file:
'use strict';
var connection = require('../../server.js');
connection.query ('select * from <table name>', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});
or
exports.get=function(req,res){
console.log(req.query.printerModel);
console.log('inside get function');
connection.query('select * from inkdetails', function(error, results){
if (results){
res.status(200).send(inkdetails)
console.log(results);
}
else{
res.status(400).send(error)
console.log(error);
}
});
};
Create a file which will handle connection and export required utility functions related to mysql and then you can initialize connection in your startup file and import that connection object in any handler.
your mysql lib:
const mysql = require('mysql');
const logger = require('your-looger-path');
const mysqlConfig = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var pool = mysql.createPool(mysqlConfig);
module.exports.connect = function (cb) {
return new Promise((resolve, reject) => {
pool.on('connection', function (connection) {
connection.on('error', function (err) {
logger.error('MySQL error event', err)
});
connection.on('close', function (err) {
logger.warn('MySQL close event', err)
});
});
resolve()
})
}
async function executeQuery (query) {
logger.debug(`query: `, query)
return new Promise((resolve, reject) => {
try{
pool.query(query, (e, r, f) => {
if(e){
reject(e)
}
else{
logger.debug(r,f)
resolve(r[0])
}
});
}
catch(ex){
reject(ex)
}
})
}
async function execSP(spName, params){
return new Promise((resolve, reject) => {
try{
var paramPlaceHolder = ''
if(params && params.length){
for(var i = 0; i < params.length; i++){
paramPlaceHolder += '?,'
}
}
if(paramPlaceHolder.length){
paramPlaceHolder = paramPlaceHolder.slice(0, -1)
}
logger.debug('final SP call', `CALL ${spName}(${params})`)
pool.query(`CALL ${spName}(${paramPlaceHolder})`, params, (e, r, f) => {
if(e){
reject(e)
}
else{
resolve(r[0])
}
});
}
catch(ex){
reject(ex)
}
})
}
module.exports.executeQuery = executeQuery
module.exports.execSP = execSP
and then create the connection in server.js file:
var express = require('express');
var cors = require('cors');
var mysqllib = require('require to your mysql wrapper created above');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mysqllib.connect().then(() => {
console.log('Connected to mysql...')
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
}).catch(e => {
console.error('Error connecting mysql...')
process.exit()
})
In your controller
'use strict';
const mysqlLib = require('your mysql lib path')
exports.get = function(req, res){
console.log(req.query.printerModel);
console.log('inside get function');
mysqlLib.executeQuery('select * from inkdetails').then((d) => {
console.log(d);
res.status(200).send(d)
}).catch(e => {
console.log(e);
res.status(500).send('Sorry, something went wrong!')
})
};
Hopes this help you.
create a config folder and create a file databaseConfig.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection =mysql.createConnection(config); //added the line
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
module.exports ={
connection : mysql.createConnection(config)
}
app.js
var express = require('express');
var cors = require('cors');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
controller.js
var config = require('../../databaseConfig.js');
var connection= config.connection
connection.query ('select * from <table name>', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});
I'm trying to display all members from MYSQL database with Node Js. But I get some errors. My database name is apibase and I have table members (id, name, email, phone) My code is below:
//routes.js file
const pool = require('../data/config');
const router = app => {
app.get('/', (request, response) => {
response.send({
message: 'Welcome to the Node.js Express REST API!'
});
});
// Display all users
app.get('/members', (request, response) => {
pool.query('SELECT * FROM members', (error, result) => {
if (error) throw error;
response.send(result);
});
});
// Display a single user by ID
app.get('/members/:id', (request, response) => {
const id = request.params.id;
pool.query('SELECT * FROM members WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
}
module.exports = router;
And my database.js file:
const mysql = require('mysql');
const config = {
host: 'localhost',
user: 'root',
password: '',
database: 'apibase',
};
const pool = mysql.createPool(config);
module.exports = pool;
And app.js file
const express = require('express');
const port = 8080;
const bodyParser = require('body-parser');
const routes = require('./routes/routes')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
routes(app);
const server = app.listen(port, (error) => {
if (error) return console.log(`Error: ${error}`);
console.log(`Server listening on port ${server.address().port}`);
});
I don't know what is the problem with this code, can somebody help me with this.
The full code is following - pretty simply i wanna add, delete or update posts - when i do one of the things by them self it works but togther it breaks
Iv'd searched alot in the NodeJS MySQL which i use to query the database
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
database: 'nodeproject',
user : 'noderoot',
password : 'default'
});
var express = require('express');
var http = require('http');
var path = require('path');
var exphbs = require('express3-handlebars');
var qs = require('querystring');
var app = express();
app.set('port', process.env.PORT || 8000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
configQuery = function() {
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
}
index = function(req, res){
/*connection.connect(function(err){
if(err != null) {
res.end('Error connecting to mysql:' + err+'\n');
}
});*/
connection.query("SELECT * FROM posts", function(err, rows){
if(err != null) {
res.end("Query error:" + err);
} else {
var myOuterRows = [];
for (var i = 0; i < rows.length; i++) {
var myRows = rows[i];
myOuterRows.push(myRows);
};
res.render('index', {
title: 'Express Handlebars Test',
posts: myOuterRows
});
}
});
};
addpost = function(req, res) {
var post = {
id: req.body.post.id,
postTitle: req.body.post.postTitle,
postContent: req.body.post.postContent,
published: req.body.post.published
};
connection.query('INSERT INTO posts SET ?', post, function(err, result) {
console.log("Neat! you entered a post");
});
res.redirect("/");
}
editpost = function(req, res) {
configQuery();
var edit = {
id: req.body.editpost.id,
postTitle: req.body.editpost.postTitle,
postContent: req.body.editpost.postContent
};
var queryTitle = connection.query("UPDATE posts SET ?", edit, function(err, result) {
console.log("Neat! you editted a post")
});
res.redirect("/");
}
deletepost = function(req, res) {
configQuery();
var deleteThis = {
id: req.body.deletepost.id
};
console.log(deleteThis);
var queryDelete = connection.query("DELETE FROM posts WHERE id = :id", {
id: deleteThis.id
});
res.redirect("/");
}
app.get('/', index);
app.post('/', addpost);
app.post('/', editpost);
app.post('/', deletepost);
//app.get('/list', list);
http.createServer(app).listen(8000, function(){
console.log('Express server listening on port ' + app.get('port'));
});
The error i get is following:
500 TypeError: Cannot read property 'id' of undefined
at editpost (C:\dev\ExpressHbsMysql\app.js:96:24)
at callbacks (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:164:37)
at param (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:138:11)
at pass (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:33:10)
at next (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.methodOverride [as handle] (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:48:5)
at next (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:83:7
Where should it go?
app.post('/', addpost);
app.post('/', editpost);
app.post('/', deletepost);
To addpost or to editpost or to deletepost
As far as i can tell from your code i suggest you keep different urls for each handler that way you will tell which handler to call, right now all your post requests call first handler which is addpost
Map your handlers like this
app.post('/post/add', addpost);
app.post('/post/edit', editpost);
app.post('/post/delete', deletepost);
Next in your forms or if your are using ajax post your addrequest to '/post/add', editrequest to /post/edit and so on.