insomnia -- Cannot read property 'post' of undefined - html

var express = require('express');
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
mongoose.Promise = require('bluebird');
mongoose.connect("mongodb://makja:q1w2e3r4#ds111123.mlab.com:11123/makja" , { useMongoClient: true });
var db = mongoose.connection;
db.once("open", function () {
console.log("DB on!");
});
db.on("error", function (err) {
console.log("DB error : " , err);
});
var dataSchema = mongoose.Schema({
name:String,
count:Number
});
var postSchema = mongoose.Schema({
title : {type:String, required:true},
body : {type:String, required:true},
createdAt : {type:Date, default:Date.now},
updatedAt : Date
});
var Post = mongoose.model('post',postSchema);
app.get('/posts', function(req , res){
Post.find({}, function(err,posts){
if (err) return res.json({success:false, message:err});
res.json({success:true, data:posts});
});
});
app.post('/posts', function(req , res){
Post.create(req.body.post, function(err,post){
if (err) return res.json({success:false, message:err});
res.json({success:true, data:post});
});
});
var Data = mongoose.model('data',dataSchema);
Data.findOne({name:"myData"},function(err,data){
if (err) return console.log("Data error",err);
if (!data) {
Data.create({name:"myData",count:0},function(err,data){
if (err) return console.log("Data error:",err);
console.log("counter initalized:",data);
});
}
});
app.set("view engine",'ejs');
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyparser.json());
app.get('/',function(req , res) {
Data.findOne({name:"myData"}, function(err,data){
if(err) return console.log("Data error: ",err);
data.count++;
data.save(function(err){
if(err) return console.log("Data error: ",err);
res.render('my_first_ejs',data);
});
});
});
app.get('/',function (req,res) {
res.render('my_first_ejs');
});
app.listen(8000, function(){`enter code here`
console.log('Server On!');
});
cmd error -------------------------------
TypeError: Cannot read property 'post' of undefined
at C:\nodejs\index.js:38:23
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)
at next (C:\nodejs\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\nodejs\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)
at C:\nodejs\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\nodejs\node_modules\express\lib\router\index.js:335:12)
at next (C:\nodejs\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\nodejs\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\nodejs\node_modules\express\lib\router\index.js:317:13)
at C:\nodejs\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\nodejs\node_modules\express\lib\router\index.js:335:12)
at next (C:\nodejs\node_modules\express\lib\router\index.js:275:10)
at query (C:\nodejs\node_modules\express\lib\middleware\query.js:44:5)
at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)

make sure your bodyparser is actually parsing body and attaching body to req before your POST is getting handled.
--> app.use(bodyparser.json());
var app = require('express')();
var bodyParser = require('body-parser');
app.post('/', (req, res) =>{
console.log(req.body); //undefined
res.json(req.body).status(200);
})
app.use(bodyParser.json());
app.listen(3000);
====
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', (req, res) =>{
console.log(req.body); //attaches correctly
res.json(req.body).status(200);
})
app.listen(3000);

Related

passport missing credentials on form post

I am developing a nodejs express application with MySQL and for the session, authentication, and authorization I am using the passport, I dont know why but when I create the account everything goes fine. User is being created.
But when I login, it returns an error message saying "Missing credentials".
I have already seen every other Stackoverflow question regarding this problem but I haven't found a solution.
app.js
const express = require("express");
const cors = require('cors');
const accountRoute = require("./routes/account");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set("view engine","ejs");
app.use(express.static(__dirname + '/views'));
app.use(accountRoute.app)
app.use(accountRoute.router);
app.get("/", (req,res) => {
res.render("index.ejs");
});
app.listen(8000, () => console.log(`Listening on port 8000...`));
Login and Register
const express = require('express');
const session = require('express-session');
const flash = require('express-flash');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const config = require('../config');
const initalizePassport = require('../passport');
const user = require('../models/user').User;
const router = express.Router();
const app = express();
initalizePassport(passport, async (email) => {
return await user.findOne({ where: { "email": email } }) === email;
}, async (id) => {
return await user.findOne({ where: { "id": id } }) === id;
});
app.use(session({
secret: config.sessionPassword,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
router.get('/login', (req, res) => {
res.render('login.ejs');
});
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
router.get('/register', (req, res) => {
res.render('register.ejs');
});
router.post('/register', async (req, res) => {
try {
const hashedPassword = await bcrypt.hashSync(req.body.userpass, 10);
user.create({
"email": req.body.email,
"username": req.body.username,
"userpass": hashedPassword
});
res.redirect('/login');
} catch (error) {
res.redirect('/register');
}
});
router.get('/unregister', (req, res) => {
res.render('unregister.ejs');
});
router.post('/unregister', (req, res) => {
res.send(req.body);
});
module.exports.router = router;
module.exports.app = app;
passport.js
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcryptjs')
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, userpass, done) => {
const user = getUserByEmail(email);
if (!user) {
return done(null, false, { message: 'No user with that email' })
}
try {
var correctPassword = false;
await bcrypt.compare(userpass, user.userpass, function (err, result) {
if (err) {
console.log(err);
}
else {
correctPassword = true;
console.log("passwords match!");
return;
}
});
if (correctPassword) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'userpass' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
Login.ejs
<h1>Login</h1>
<% if(messages.error) { %>
<%= messages.error %>
<% } %>
<form action="/login" method="post">
<input name="email" type="text" placeholder="email">
<input name="userpass" type="password" placeholder="userpass">
<input type="submit" value="submit">
</form>
Now it's throwing me this:
Error: Illegal arguments: string, undefined
at _async (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:286:46)
at C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:307:17
at new Promise (<anonymous>)
at Object.bcrypt.compare (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:306:20)
at Strategy.authenticateUser [as _verify] (C:\Users\datte\Desktop\auth\passport.js:13:24)
at Strategy.authenticate (C:\Users\datte\Desktop\auth\node_modules\passport-local\lib\strategy.js:90:12)
at attempt (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:366:16)
at authenticate (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:367:7)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:317:13)
at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
Executing (default): SELECT `id`, `email`, `username`, `userpass`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`email` = 'myemail' LIMIT 1;

How to import mysql connection in another file in nodejs?

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);
}
});

nodejs form cannot read property 'docreate' of undefined

I'm a new in nodejs, and trying to create a new MVC application with expressjs. I have a html form with "POST" method and when i submit that some error showing.
Cannot read property 'docreate' of undefined
TypeError: Cannot read property 'docreate' of undefined
at exports.save (C:\Users\Hieu Vo\Desktop\hellow\notes\routes\notes.js:13:18)
at Layer.handle [as handle_request] (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (C:\Users\Hieu Vo\Desktop\hellow\notes\node_modules\express\lib\router\layer.js:95:5)
here is app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var notes = require('./routes/notes');
var app = express();
// view engine setup
app.use('/noteadd', notes.add);
app.post('/notesave', notes.save);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I have view file with name noteedit.ejs
<% include top %>
<p value='<%= docreate ? "create" : "update"%>'><%= docreate ? "create" : "update"%></p>
<form method='POST' action='/notesave'>
<input type='hidden' name='docreate' value='<%= docreate ? "create" : "update"%>'>
<p>Key: <input type='text' name='notekey' value='<%= note ? notekey : "" %>'></p>
<p>Title: <input type='text' name='title' value='<%= note ? note.title : "" %>'></p>
<br/>
<textarea rows=5 cols=40 name='body'><%= note ? note.body : "" %></textarea>
<br/>
<input type='submit' value='Submit' />
</form>
<% include bottom %>
and this is my save function
var notes = require('../models/notes');
exports.add = function(req, res, next) {
res.render('noteedit', {
title: "Add a note",
docreate: true,
notekey: "",
note: undefined
});
}
exports.save = function(req, res, next) {
if (req.body.docreate === 'create') {
notes.create(req.body.notekey,
req.body.title,
req.body.body);
} else {
notes.update(req.body.notekey,
req.body.title,
req.body.body);
}
res.redirect('/noteview?key='+req.body.notekey);
}
please help me in my problem, thank you for your help.
Thank again.
I think you should use 'body-parser'. Please Read this
In this part of the code:
exports.save = function(req, res, next) {
if (req.body.docreate === 'create') {
notes.create(req.body.notekey,
req.body.title,
req.body.body);
} else {
notes.update(req.body.notekey,
req.body.title,
req.body.body);
}
res.redirect('/noteview?key='+req.body.notekey);
}
You are trying to get the property docreate of req.body and the error is saying that that property doesn't exist. Make sure it is defined before checking if it is equal to 'create'

TypeError: Converting circular structure to JSON in nodejs while transferring data from server to html page?

I am trying to run a program on server that insert the data into mongodb and retrive it .
when i am trying to insert data it inserted but the server goes down .
my server code is
server.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
methodOverride = require('method-override'),
hostname = process.env.HOSTNAME || 'localhost',
port = parseInt(process.env.PORT, 10) || 4004,
publicDir = process.argv[2] || __dirname + '/public';
var exec = require('child_process').exec;
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
//Show homepage
app.get("/", function (req, res) {
res.redirect("/index.html");
console.log("shubham ");
});
app.get("/index/", function (req, res) {
res.redirect("/index.html");
console.log("shubham ");
});
app.get("/search", function (req, res){
console.log("shubham batra");
var pro_name = req.query.name;
var pro_code = req.query.code;
var pro_category = req.query.category;
var pro_brand = req.query.brand;
MongoClient.connect('mongodb://127.0.0.1:27017/prisync', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
var documen = {name:pro_name, code:pro_code , category:pro_category, brand:pro_brand };
//insert record
db.collection('urlinfo').insert(documen, function(err, records) {
if (err) throw err;
});
db.collection('urlinfo').find({} , function(err , products){ // LINE 48 ==========
if(err){
console.log(err);
res.json(err);
}else{
res.json(products); // LINE 53 ====================
}
});
});
});
//Search page
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(publicDir));
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
console.log("Server showing %s listening at http://%s:%s", publicDir, hostname, port);
app.listen(port);
and give following error :
/home/shubham/node_modules/mongodb/lib/utils.js:97
process.nextTick(function() { throw err; });
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at ServerResponse.json (/home/shubham/Music/pricesync/server/node_modules/express/lib/response.js:242:19)
at /home/shubham/Music/pricesync/server/server.js:53:9
at handleCallback (/home/shubham/node_modules/mongodb/lib/utils.js:95:12)
at Collection.find (/home/shubham/node_modules/mongodb/lib/collection.js:339:44)
at /home/shubham/Music/pricesync/server/server.js:48:28
at /home/shubham/node_modules/mongodb/lib/mongo_client.js:439:11
at process._tickCallback (node.js:448:13)

Cannot read property 'id' of undefined. Express

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.