In express.js POST method not getting called - mongodb

I'm trying to put up a simple form handling project. The post method is not getting called. There is no output from the post method. I do not understand why this is happening. What is the issue here?
This is the code I'm using.
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var personSchema = mongoose.Schema({
name: String,
age: Number,
nationality: String,
});
var Person = mongoose.model('Person', personSchema);
app.get('/', function(req, res) {
res.render('person');
});
app.set('view engine', 'pug');
app.set('views', './views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(upload.array());
app.use(express.static('public'));
app.post('/', function(req, res) {
var personInfo = req.body; //Get the parsed information
if (!personInfo.name || !personInfo.age || !personInfo.nationality) {
res.render('show_message', {
message: 'Sorry, you provided worng info',
type: 'error',
});
} else {
var newPerson = new Person({
name: personInfo.name,
age: personInfo.age,
nationality: personInfo.nationality,
});
newPerson.save(function(err, Person) {
if (err) res.render('show_message', { message: 'Database error', type: 'error' });
else
res.render('show_message', {
message: 'New person added',
type: 'success',
person: personInfo,
});
});
}
});
app.listen(3000);
I would like to know how to fix this issue.
I tried putting a console.log() output to log if the post method is being called. But there was no output from it either.

Related

Mongoose data is not saved to db

I'm trying to use mongoose/express to add form data to a db. The collection is created within the database and although there are no errors when submitting, and my console.log confirms the data is there along with a generated ID i still don't have any entries within the database, can you see what I'm missing? Any help would be really appreciated.
**CONFIG**
const port = process.env.PORT || 3000,
bodyparser = require("body-parser"),
mongoose = require("mongoose"),
express = require("express"),
app = express();
app.set("view engine", "ejs");
app.use(
bodyparser.urlencoded({
extended: true
})
);
app.use(
require("express-session")({
secret: "Mama Mia Thats a Spicy Meatball!",
resave: false,
saveUninitialized: false
})
);
app.use(express.static(__dirname + "/styles/"));
app.use(express.static(__dirname + "/Media/"));
app.use(express.static(__dirname + "/JS/"));
mongoose.connect("mongodb://localhost/lashB", {
useNewUrlParser: true
});
const mongCon = mongoose.connection;
mongCon.on("connected", function () {
console.log(`beep boop
database mainframe syncroniiiiiiized`);
});
mongCon.on("disconnected", function () {
console.log(`You're off the database now...Daniel San.`);
});
mongCon.on('error', function () {
console.log(error, `We've got company...there's an error!!!`);
});
**SCHEMA**
var customerSchema = new mongoose.Schema({
firstName: String,
lastName: String,
mobile: String,
email: String,
treatment: String,
time: String,
date: Date
});
var Customer = mongoose.model("Customer", customerSchema, "Customer");
**ROUTES**
app.get("/", function (req, res) {
res.render("main");
});
app.get("/appointment", function (req, res) {
res.render("appointment");
});
app.get("/appointmentConfirmation", function (req, res) {
res.render("appConfirmation");
});
app.get("/blogHome", function (req, res) {
res.render("blogHome");
});
app.post('/appointment', function (req, res) {
var firstName = req.body.firstName,
lastName = req.body.lastName,
mobile = req.body.mobile,
email = req.body.email,
treatment = req.body.treatment,
time = req.body.time,
date = req.body.date;
var deetz = {
date: date,
time: time,
treatment: treatment,
email: email,
mobile: mobile,
firstName: firstName,
lastName: lastName
}
Customer.create(deetz, function (err, info) {
if (err) {
console.log(err, `something went wrong`);
} else {
console.log(info);
console.log('newly created file for a customer');
}
});
res.render('appConfirmation', {
firstName: firstName
}
);
});
app.listen(port, function () {
console.log(`You rockin' now on port ${port}`);
});
Fixed it. The mistake was that i was entering 'use' nameofcollection, but 'use' is for the db and not collections. So show dbs > use nameofdb > db.nameofcollection.find() worked just fine.

Error 404 Not Found Using Pug & Express and MongoDB

I am getting at 404 not found error using Express & MongoDB for a POST request. I tried to redo my routes numerous times, but am having trouble with the login page. I want to POST the information to my server and render a simple "Welcome Message."
Please advise.
Routes Folder:
var express = require('express');
var router = express.Router();
let mongoose = require('mongoose');
var User = require('../models/users')
//Get registration page from index button//
router.get('/register', function(req, res, next) {
res.render('register');
if (err) return console.error(err);
res.json(user);
});
//Post user data to database POST /register //
router.post('/register', function(req, res, next) {
res.render('Welcome to Fit 7');
})
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var newuser = new User();
newuser.username = username;
newuser.email = email;
newuser.password = password;
newuser.save(function(err, savedUser) {
if(err) {
console.log(err);
return res.status(500).send();
}
return res.status(200).send();
})
module.exports = router;
App JS Code:
// var createError = require('http-errors');
var express = require('express');
var app = express();
var path = require('path');
// var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var pug = require('pug');
// var indexRouter = require('./routes/index');
var workouts = require('./routes/workouts');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
// app.use(cookieParser());
// app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', indexRouter);
// app.use('/api/workouts', workouts);
app.get('/', function (req, res) {
res.render('index')
})
//Registration Route for New Users
app.get('/register', function (req, res) {
res.render('register')
});
app.get('/home', function (req, res) {
res.render('home');
});
app.get('/workout/new', function (req, res) {
res.render('workoutform');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);});
// 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;
Pug Template Code:
body(data-gr-c-s-loaded='true', style='')
.container
form(action='/register', method='post').form-signin
h1.form-signin-heading Login to Fit-7
label.sr-only(for='username') Name
input#name.form-control(type='username', placeholder='username',
required='', autofocus='')
label.sr-only(for='email') Email address
input#inputEmail.form-control(type='email', placeholder='email address',
required='', autofocus='')
label.sr-only(for='password') Password
input#password.form-control(type='password', placeholder='password',
required='')
button.btn.btn-lg.btn-primary.btn-block(type='submit') Sign in
span._hsShareImage.hsShareImage  
loom-container#lo-engage-ext-container
loom-shadow(data-reactroot='', classname='resolved')
You dont seem to import the router anywhere in your app.js. First add
var registerRoute = require("./path/to/route.js");
after your other requires. Then add
app.use(registerRoute)
in place of this line:
app.get('/register', function (req, res) {
res.render('register')
});
I still dont have a reputation to like the comment above or comment, but the answer was very helpful.
But my problem was that I had the bellow line:
app.use('/', routes);
So I changed to where my application was
app.use('/Live/api', routes);
I'm using express with pug

MongoDB document not saved but showing success

I have a problem. I'm trying to save answers from a survey. My problem is that I'm sending these answers through axios and they are showing in the console.log from the server, which means that my data is reaching the server safely. But data is not being saved. Also no error is shown.
Server.js
router.route('/answers')
//post answers to database
.put(function(req, res){
var survey = new Survey();
survey.name = req.body.name;
survey.email = req.body.email;
survey.q_id = req.body.q_id;
survey.q_text = req.body.q_text;
survey.answer = req.body.answer;
console.log(Survey.collection)
survey.save(function(err){
if(err){
console.log(err)
return ;
}
res.send(survey);
});
})
Survey.js (Model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var question = new Schema({
q_text:String,
order: Number,
options:[{
type: {type: String},
value: {type: String}
}]
});
module.exports = mongoose.model('Question',question);
Code that is posting the data
const url = 'http://localhost:3100/api/answers';
axios.put(url, survey)
.then(res => {
console.log('Successfully posted');
console.log(res);
setSubmitting(false);
setStatus({submitted: true});
})
.catch(err => {
console.log(err);
})
Try this :
survey.save(function(err, savedSurvey){
if(err){
console.log(err)
return ;
}
res.send(savedSurvey);
});

Can't set headers after they are sent. Error when Creating a sub-document with Mongo

I am trying to create a sub-document with my express API through postman with the following request:
POST /api/course/58c6f76e06e6edda1b000007/subject/58c6f85280a5d6591c000007/question
I am also sending x-www-forum-urlencoded data with names question and answer.
Here is the error that is output in the terminal:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/response.js:719:10)
at ServerResponse.send (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/response.js:164:12)
at ServerResponse.json (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/response.js:250:15)
at sendJSONResponse (/home/tyler/Dropbox/Projects/Curricula/API/controllers/question.js:8:8)
at Promise.<anonymous> (/home/tyler/Dropbox/Projects/Curricula/API/controllers/question.js:36:10)
at Promise.<anonymous> (/home/tyler/Dropbox/Projects/Curricula/node_modules/mpromise/lib/promise.js:171:8)
at emitOne (events.js:77:13)
at Promise.emit (events.js:169:7)
at Promise.emit (/home/tyler/Dropbox/Projects/Curricula/node_modules/mpromise/lib/promise.js:88:38)
Here is my controller file and relevant data models:
var mongoose = require('mongoose');
var Course = mongoose.model('Course');
var Subject = mongoose.model('Subject');
var Question = mongoose.model('Question');
var sendJSONResponse = function(res, status, content){
res.status(status);
res.json({content});
};
var addQuestion = function(req, res, subject){
if(!subject){
sendJSONResponse(res, 404, {"message":"subjectid not found"});
return;
}
else{
subject.questions.push({question: req.body.question,
answer: req.body.answer,
falseAnswer: req.body.falseanswer});
subject.save(function(err, course){
var thisQuestion
if(err){
sendJSONResponse(res, 400, err);
} else{
thisQuestion = subject.questions[subject.questions.length - 1];
sendJSONResponse(res, 201, thisQuestion);
}
});
}
}
var seekSubject = function(req, res, course){
if(req.params && req.params.subjectid){
Subject.findById(req.params.subjectid).exec(function(err, subject){
if(!subject){
sendJSONResponse(res, 404, {"message":"subjectid not found"});
}
else if(err){
sendJSONResponse(res, 404, err);
return;
}
sendJSONResponse(res, 200, subject);
return subject
});
} else{
sendJSONResponse(res, 404, {
"message":"no subjectid in request"
});
}
};
module.exports.makeQuestion = function(req, res){
var courseid = req.params.courseid;
if(courseid) Course.findById(courseid).select('subjects').exec(
function(err, course){
if(err){
sendJSONResponse(res, 400, err);
return;
}
else var subject = seekSubject(req, res, course);
addQuestion(req, res, subject);
});
}
Course Model
var mongoose = require('mongoose')
var subject = require('./subject.js');
var courseSchema = new mongoose.Schema({
name : {type: String,
unique: true,
required: true},
subjects : [subject.schema]
});
Subject Model
module.exports = mongoose.model('Course', courseSchema);
var mongoose = require('mongoose')
var question = require('./question.js');
var subjectSchema = new mongoose.Schema({
name : String,
questions : [question.schema]
});
module.exports = mongoose.model('Subject', subjectSchema);
Question model
var mongoose = require('mongoose')
var questionSchema = new mongoose.Schema({
question: {type: String, required: true},
answer: {type: String, required: true},
falseAnswer: [String]
});
module.exports = mongoose.model('Question', questionSchema);
What am I doing wrong in creating the entry?
It could be in this area
else var subject = seekSubject(req, res, course);
addQuestion(req, res, subject);
those 2 function, seekSubject and addQuestion seem like that are both calling sendJSONResponse and they both seem like that they sending a response
res.status(status); res.json({content});
So if both functions are being called in that area you are likely sending 2 responses and that is why you are getting that error.
You are doing good by separating the concerns but you got to get the error stuff separate too. your telling the server to respond twice when you call the 2 function. I think your calling both functions. I haven't ran your code.
You get this because you are sending 2 responses when you should send just 1. Try doing the following:
res.status(500).json({ error: 'message' });
Or you might want to try using return before sendJSONResponse(res, status, content); like so for example:
return sendJSONResponse(res, 404, {"message":"subjectid not found"});
Hope this helps you out.

Why wont this post?

I'm playing around with mongodb + Express and rewriting an old comments app in the latest version of Express.
I've had to change a few things because of the changes in the latest Express. But I'm having some issues.
Basically, it won't post to /create when I submit my form. This is probably a simple fix but any help would be appreciated :)
app.js
require('./models/comments'); // require the model before the 'index.js' file is called
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser');
var routes = require('./routes/index'); var create = require('./routes/create');
var app = express();
// Database stuff var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/comments-app');
// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');
app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes); app.use('/create', create);
/// catch 404 and forward to error handler app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err); });
/// error handlers
// development error handler // will print stacktrace if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
}); }
// production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
}); });
module.exports = app;
Comments.js (model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
username: String,
content: String,
created: Date
});
module.exports = mongoose.model('Comment', CommentSchema);
index.jade
extends layout
block content
h1= title
div.addCommentForm
form( method="post", action="/create")
input(type='text', class='nameTxt', name='username')
div
span.label Comment :
textarea(name='comment')
div#addCommentSubmit
input(type='submit', value='Save')
br
br
#comments
- each comment in comments
div.comment
div.name comment.username
div.created_at= comment.created
br
div.content= comment.content
hr
create.js (route)
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment', Comment);
router.route('/create')
.post(function(req, res) {
var Comment = new Comment()
username : req.body.username;
content : req.body.comment;
created : Date.now();
Comment.save(function(err) {
if (err)
res.send(err);
res.send('Comment added');
});
});
module.exports = router;
Your jade indenting for the form tag is off. Make sure the input tags you want inside the form tag in the HTML are indented further than the form tag in your jade so they end up as children of the form tag in the HTML.
Oops:
this jade
form
input
yields this HTML
<form></form><input>
Fixed
form
input
yields
<form><input></form>