Data not getting saved in the MongoDB from node.js - json

I want to create the rest api using node.js and mongodb
I am entering all the details and trying it to store it in the mongodb database.
// call the packages we need
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
// configure app
app.use(morgan('dev')); // log requests to the console
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
var mongoose = require('mongoose');
// mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o'); // connect to our database
mongoose.connect('mongodb://localhost:27017');
var Bear = require('./app/models/bear');
// create our router
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next();
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
bear.email= req.body.email; // set the bears email(comes from the request)
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
// get all the bears (accessed at GET http://localhost:8080/api/bears)
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')
// get the bear with that id
.get(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
res.json(bear);
});
})
// update the bear with this id
.put(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
bear.name = req.body.name;
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear updated!' });
});
});
})
// delete the bear with this id
.delete(function(req, res) {
Bear.remove({
_id: req.params.bear_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
// REGISTER OUR ROUTES -------------------------------
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
The Model is given below:-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String,
email: String
});
module.exports = mongoose.model('Bear', BearSchema);
I am trying it to save the name and the email in the mongodb database but only _id is created instead of name, email.
Here is the result:-
[
{
"_id": "567f1f92db24304013000001",
"__v": 0
},
{
"_id": "567f2765db24304013000002",
"__v": 0
}
]
Can anybody tell me why the data are not getting saved in the database.
Please kindly help.
Thanks in Advance.

I think your POST request is not good, so I made this simple script to check it out:
var XHR = (function() {
var _xhr = (function() {
try {
return new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
} catch (e) {}
})();
return function(method, url, params, callback) {
_xhr.onreadystatechange = function() {
if (_xhr.readyState == 4) {
var _response;
try {
_response = JSON.parse(_xhr.response);
} catch (e) {
_response = _xhr.responseText;
}
if (_xhr.status != 200) {
// catch an error
console.error('error', response);
} else {
if (callback) {
callback(_response);
} else {
// deal with it
}
}
}
}
if (!params) {
params = JSON.stringify({});
} else {
params = JSON.stringify(params);
}
_xhr.open(method, url, true);
// just json in this case
_xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
_xhr.send(params);
};
})();
fire it up in browser's console, like this
XHR('POST','api/bears', { name:'yogi', email:'yogi#bears.com'}, function(){ console.log(arguments) });
and your record will be saved.
{ "_id" : ObjectId("567e875d068748ee5effb6e0"), "email" : "yogi#bears.com" "name" : "yogi", "__v" : 0 }
Long story short - your code is okay, your POST is not.

Related

Where to place code to show data from MySQL to Handlebars?

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

How can i resolve 'Cannot set headers after they are sent to the client'

How can I resolve Cannot set headers after they are sent to the client:
app.js
var express = require('express');
var session = require('express-session');
var mongoose = require('mongoose');
var app = express();
var ejs = require('ejs');
var port = 3000;
var bodyParser = require('body-parser');
var mongoDB = "mongodb://localhost:27017/vinavdb";
app.set('views', __dirname + '/admin') app.engine('html', ejs.renderFile);
app.set('view engine', 'ejs');
app.set('trust proxy', 1);
app.use(session({
secret: 'dsghbrtdfhbdfg64545TRYFFHGGJNN',
resave: false,
saveUninitialized: true
}))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var sess;
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, {
useNewUrlParser: true
});
var nameSchema = new mongoose.Schema({
firstname: String,
lastname: String,
email: String,
password: String
});
var User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
sess = req.session;
if (sess.email) {
res.redirect("/admin");
} else {
res.sendFile(__dirname + "/index.html");
}
});
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/login.html");
});
app.post("/addname", function(req, res) {
var myData = new User(req.body);
User.findOne({
email: req.body.email
}, function(err, resv) {
if (resv == null) {
myData.save().then(item => {
res.send("Name saved to database")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
res.send("ThankYou For your Registration")
} else if (resv.email == req.body.email) {
res.send("Email is already registered");
} else {
res.send("Srry data is not allowed");
}
});
});
app.post("/login", function(req, res, next) {
User.findOne({
email: req.body.email
}, function(err, vals) {
if (vals == null) {
res.end("Invalid Logins");
} else if (vals.email == req.body.email && vals.password == req.body.password) {
sess = req.session;
sess.email = req.body.email;
res.redirect('/admin');
} else {
res.send("Srry data is not allowed");
}
});
});
app.route('/admin').get(function(req, res, next) {
sess = req.session;
if (sess.email) {
res.send(__dirname + "/admin/index.html");
} else {
res.write('Please login first.');
}
})
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Cause of your error : You are trying to send a response of a single request twice.
One request have one response.
Once response is send, you cannot send it again for the same request.In your /addname API, You are trying to send response twice. So remove one.
Here .save() is asynchronous function so node will not wait and execute
res.send("ThankYou For your Registration") first and later once record will be saved it will try to send res.send("Name saved to database") so you are getting error here.
app.post("/addname", function(req, res) {
var myData = new User(req.body);
User.findOne({
email: req.body.email
}, function(err, resv) {
if (resv == null) {
myData.save().then(item => {
console.log("Name saved to database")
res.send("ThankYou For your Registration")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
} else if (resv.email == req.body.email) {
res.send("Email is already registered");
} else {
res.send("Srry data is not allowed");
}
});
});
After you execute a res.send you cannot call it again in the same request, it only allows one response per request. In your code, I think in this part it can happens:
if (resv == null) {
myData.save().then(item => {
res.send("Name saved to database")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
res.send("ThankYou For your Registration")
}
In this if, when you are saving myData you are sending a response, but asynchronously you already sent another response previously ("ThankYou For your Registration").
Hope it helps

error: POST http://localhost:3000/api/createProductCategory 500 (Internal Server Error)

I am trying to insert data into a table using POST method for that I have a angular service function
angular.module("productCategoryModule")
.factory("productCategoryService",productCategoryService);
productCategoryService.$inject = ['$http'];
function productCategoryService($http){
return {
createProductCategory:function(productCategory){
console.log("createProductCategory in service called",productCategory);
return $http.post('/api/createProductCategory',
{
categoryName:productCategory.categoryName,
details:productCategory.categoryDetails
}
);
},
getAllProductCategories:function(){
return $http.get('/api/getAllProductCategory');
}
}
}
and at server side I have
function productCategoryRouteConfig(app){
this.app = app;
this.routeTable = [];
this.init();
}
productCategoryRouteConfig.prototype.init = function(){
var self = this;
this.addRoutes();
this.processRoutes();
}
productCategoryRouteConfig.prototype.processRoutes = function(){
var self = this;
self.routeTable.forEach(function(route){
if(route.requestType == 'get'){
//console.log("requestType",route.requestType)
self.app.get(route.requestUrl,route.callbackFunction);
} else if(route.requestType == 'post'){
//console.log("requestType",route.requestType);
self.app.post(route.requestUrl,route.callbackFunction);
} else if(route.requestType == 'delete'){
}
});
}
productCategoryRouteConfig.prototype.addRoutes = function(){
var self = this;
self.routeTable.push({
requestType: 'get',
requestUrl: '/createProductCategory',
callbackFunction: function(req, res){
res.render('createProductCategory',{title:'Create Product Category'});
}
});
self.routeTable.push({
requestType: 'post',
requestUrl: '/api/createProductCategory',
callbackFunction: function(req, res){
console.log("Post called");
//res.render('createProductCategory');
console.log("req.body",req.body);
var productCategoryDb = require('../database/productCategoryDb');
// console.log("productCategoryDb post",productCategoryDb);
// console.log("hello from createProductCategory post");
// console.log("req.body",req.body);
// productCategoryDb.productCategoryDb.createProductCategory(req.body, function(status){
// if(status)
// res.json(status);
// console.log(status);
// });
}
});
self.routeTable.push({
requestType: 'get',
requestUrl: '/viewProductCategory',
callbackFunction: function(req, res){
res.render('viewProductCategory',{title:'View Product Category'});
}
});
self.routeTable.push({
requestType: 'get',
requestUrl: '/api/getAllProductCategory',
callbackFunction: function(req, res){
console.log("hello from getAllProductCategory");
var productCategoryDb = require('../database/productCategoryDb');
console.log("productCategoryDb",productCategoryDb);
// productCategoryDb.productCategoryDb.getAllProductCategories(
// function (productCategories){
// console.log("productCategories",productCategories);
// res.json({productCategories : productCategories});
// }
// );
}
});
}
module.exports = productCategoryRouteConfig;
when I click on the button on client side I get this error
POST http://localhost:3000/api/createProductCategory 500 (Internal Server Error)
I am using Node express mysql and angular.
There are three files in me database folder.
1.connectionString.js
var mysqlConnectionString = {
connectionString:{
host:'localhost',
user:'root',
password:'root',
database:'vidzy'
}
}
//module.exports = mysqlConnectionString;
exports.mysqlConnectionString = mysqlConnectionString;
2.connection.js
var mysql = require('mysql');
var mysqlConnectionString = require('/home/ep-3/node-express/yt_tutorial/database/connectionString.js');
var connectionStringProvider = {
getSqlConnection:function(){
var connection = mysql.createConnection(mysqlConnectionString.mysqlConnectionString.connectionString);
connection.connect(function(err){
if(err){
throw err;
} else{
console.log("connection was successful");
}
});
return connection;
},
closeSqlConnection:function(currentConnection){
currentConnection.end(function(err){
if(err){
throw err;
} else{
console.log("Disconnected");
}
})
}
}
exports.connectionStringProvider = connectionStringProvider;
3.productCategoryDb.js
var connectionProvider = require('/home/ep-3/node-express/yt_tutorial/database/connection.js');
var productCategoryDb = {
createProductCategory : function(productCategory, onSuccessful){
var insertStatement = 'INSERT INTO productcategory SET?';
var category = {
categoryName : productCategory.categoryName,
Details : productCategory.details,
isValid : productCategory.isValid,
CreatedDate : new Date()
}
var connection = connectionProvider.connectionStringProvider.getSqlConnection();
if(connection){
connection.query(insertStatement, category, function(err, result){
if(err){
console.log(err);
}
onSuccessful({status : 'Successful'});
console.log(result);
});
connectionProvider.connectionStringProvider.closeSqlConnection(connection);
}
},
getAllProductCategory : function(callback){
var connection = connectionProvider.connectionStringProvider.getSqlConnection();
var selectStatement = 'SELECT * FROM productcategory';
if(connection){
connection.query(selectStatement, function(err, rows, fields){
if(err){ through err; }
console.log(rows);
callback(rows);
});
}
}
}
exports.productCategoryDb = productCategoryDb;
Are you sure you have included the module body-parser.
It seems the code you posted here to be the same as the tutorial I have been following.
Your code seems to be fine except I don't know what your code in app.js looks like.
I have verified that I get the console response for req.body as undefined when I comment out the module body-parser.
I got the same error but in my case there was a node-modules function that increments id for each POST I made and i forgot to add id in my DTO..and now it's working; maybe it's not your case since u are using mysql but I'll post the answer anyway, maybe some1 will resolve his error thank to this help

mysql million rows express.js slow response

I am using node.js v0.10.33 with node-mysql 2.5.4 and express.js 4.10.2 and fast-csv 0.6.0
Any following requests made to the server slows down after a request to "query 9000000 rows and download it as csv". Is there a better way to avoid the slow response?
/**
* problem is why the server response slows down on a large request mande to mysqlrows_to_csv which queries 9000000 rows and saves as csv
*/
(function () {
'use strict';
var async = require('async');
var csv = require("fast-csv");
var fs = require('fs');
var mysql = require('mysql');
//var express = require('express');
//var expRouter = express.Router(); // Express Router
expRouter.get('/mysqlrows_to_csv/', function(req, res, next) {
mysqlrows_to_csv(function(err) {
console.log('use socket to emit a notification to client saying csvfile is ready');
});
res.json({'mysqlrows_to_csv': true});
return res.end();
});
expRouter.get('/some_other_queries/', function(req, res, next) {
res.json({'some_other_queries': true});
return res.end();
});
function mysqlrows_to_csv(callback) {
var csvStream;
var connProp = {
host : 'host',
user : 'user',
password : 'password',
database : 'database'
};
var I = 0;
async.waterfall([
function(cb) {
var connection = mysql.createConnection(connProp);
connection.connect(function(err) {
if (err) return callback(err);
csvStream = csv.createWriteStream({headers: true});
var writableStream = fs.createWriteStream("dump_mysql_to_csv.csv");
writableStream.on("error", function(err){
return callback(err);
});
writableStream.on("finish", function(){
console.log("DONE!");
return callback(null);
});
if (csvStream) csvStream.pipe(writableStream);
return cb(err, connection);
});
},
function(connection, cb) {
var qry = 'select * from table'; // this has aleast 9000000 rows
var query = connection.query(qry);
query
.on('error', function(err){
return cb(err);
})
.on('result', function(row) {
connection.pause();
I = I + 1;
console.log('row no.', I);
if (csvStream) csvStream.write(row);
connection.resume();
})
.on('end', function() {
console.log('stream-ended')
if (csvStream) csvStream.end();
return cb(null, connection);
});
},
function(connection, cb) {
connection.end(function(err) {
if (err) {
console.log('Error while disconnecting mysql', err);
}
console.log('The connection is terminated now');
console.log('final conn state:', connection.state);
});
}
]);
}
}());

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.