Express.js request.body not working - node.js

I have a simple form for login, the problem is when i press "Submit", the request.body on server side is empty.I saw that bodyParser is a fundamental part but in my case it's declared before the routes, so i think the problem is another. this is my server page App.js
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// 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');
});
app.listen(3000);
module.exports = app;
this is index.js
var express = require('express');
var router = express.Router();
function Login(req, res){
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect('mongodb://localhost:27017/squaredDB', function(err, db) {
if(err) throw err;
db.collection('users').find({email: req.body.email}, function(err, data){
console.log(req.body);
});
});
}
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
Login(req, res);
res.render('app-home', { title: '' });
});
module.exports = router;
this is my jade template form:
form(method="post" action="/")
label Email
input(type="text" placeholder="Email")
label Password
input(type="password" placeholder="Password")
input(type="submit" value="login")

You're missing name attributes for your input fields in your template. Without those the browser won't submit them in the form.

Add a name attribute to your input field it will now be able to access the field via request like req.body.name
<form action="/", method="POST">
<input type="text" placeholder="name" name="name">
<button type="submit">Submit</button>
</form>

Related

Node.js & Express Form Submit returns 404

I'm trying to make a simple file upload system but everytime I submit my uploaded file I get a 404 error. I've tried various different names and paths but all of them fail instantly. When I press submit, the browser tries to redirect to /upload then returns the 404 error. I'm new to node.js so it may as well be very simple to solve but I couldn't find it.
I've tried 2 different modules, formidable and express-fileupload. Both return the same error.
./views/test2.ejs
<html>
<head>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
</body>
./routes/test2.js
var express = require('express');
var router = express.Router();
var http = require('http');
var formidable = require('formidable');
router.get('/', function (req, res, next) {
res.render('test2');
res.sendFile(__dirname + '/test2.ejs');
});
router.post('/upload', function (req, res, next) {
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin', function (name, file) {
file.path = __dirname + '/uploads/' + file.name;
});
form.on('file', function (name, file) {
console.log('Uploaded ' + file.name);
});
res.sendFile(__dirname + '/test2.ejs');
});
module.exports = router;
./app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect("REDACTED", function(err,db){
if(!err){
console.log("Connected");
}
});
var index = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var form = require('./routes/form');
var buttonrelay = require('./routes/buttonrelay');
var tesekkurler = require('./routes/tesekkurler');
var test = require('./routes/test');
var test2 = require('./routes/test2');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(expressLayout);
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressValidator());
// Express Session
app.use(session({
secret: REDACTED,
saveUninitialized: true,
resave: true
}));
app.use('/', index);
app.use('/users', users);
app.use('/login', login);
app.use('/form', form);
app.use('/buttonrelay', buttonrelay);
app.use('/tesekkurler', tesekkurler);
app.use('/test', test);
app.use('/test2', test2);
// 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;
you used app.use('/test2', test2); for the /upload routing
So form action should be "/test2/upload"

Error 404 not found error

In my index.ejs, there is a link which links to /signup:
Sign Up Here
This is my app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//connect to mysql
var mysql = require('mysql');
var bodyParser = require('body-parser');
var connection = mysql.createConnection({
host:'localhost',
user: 'root',
password: '',
database: 'test'
});
connection.connect();
global.db = connection;
// all environments
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
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');
});
app.get('/',indexRouter); //call to index site
app.get('/login', indexRouter); // call to login site
app.get('/signup', usersRouter);
module.exports = app;
this is my users.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
message = '';
if(req.method == "POST"){
//post data
} else {
res.render('signup.ejs');
}
});
module.exports = router;
In my index page there is a link which link which directs user to a signup page. When I click on the link which is supposed to direct me to "http://localhost:3000/signup", it shows Error 404 Not found error. I am new to NodeJs. Any help is much appreciated. Thank you.
Changed the link in index.ejs to
Sign Up Here
Added this handler to users.js
router.get('/signup',function(req,res,next){
message = '';
if(req.method == "POST"){
//post data
} else {
res.render('signup');
}
});

Extract data from form and add to database using Mongoose

I want to simply display usernames and age on the webpage using Express Node.js and Mongoose/
The view should get updated on the left while the form is at the right. Refer this image.
Below is my users.js (/users route) followed by html of the form.
Bodyparser has been included in app.js of this application.
On clicking submit, 404 not found is thrown.
Refer this error image
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('userview');
});
router.post('#', function(req, res, next) {
//User is the model created in app.js of this project
var newUser = userModel({
name:req.body.name,
age: req.body.age
});
console.log(newUser);
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
});
module.exports = router;
<form method="post">
Name:
<input type="text" name="name"><br><br>
Age:
<input type="number" name="age"><br><br>
<input type="submit" value="Submit">
</form>
Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var applist = require('./routes/applist');
var mongoose=require('mongoose');
var app = express();
//set database connection
mongoose.connect('mongodb://localhost:27017/users');
mongoose.connection.on('error',function(){
console.log('MongoDB Connection Error. Please make sure that MongoDB is running');
process.exit(1);
});
mongoose.connection.once('open',function(callback){
console.log('Connected to Database');
});
var userSchema = new mongoose.Schema({
name:{type:String,uppercase:true},
age:Number
},{collection:'userlist'});
//make model
var userModel = mongoose.model('userModel',userSchema);
app.get('/users', function(req, res, next) {
userModel.find({},function(err,userModel){
res.render('userview',{userlist:userModel});
})
});
module.exports = userModel;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// 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;
userModel is present in app.js
On the view change
name = "fullname" to name="name"
userview
<form method="post">
Name <input type="text" name="name"><br><br>
Age<input type="number" name="age"><br><br>
<input type="submit" value="Submit">
</form>
First of all, to use req.body you need to use body-parser or busboy, connect-busboy, multiparty, connect-multiparty, formidable, multer etc. - see:
https://github.com/expressjs/body-parser
Also, what is this route supposed to be:
router.post('#', function(req, res, next) {
This character is not valid in the URL path amd needs to be URL-encoded on the client side to work. Are you sure that this is the route your need?
If you are thinking about the fragment part of the URL (as in http://host/path#fragment) then it is not sent during the HTTP request at all. See:
https://en.wikipedia.org/wiki/Fragment_identifier

HTTP post request parameters doesn't change default values of Mongoose schema

I created two Mongoose schemas and want to test them with Postman.
When I send a post HTTP request my parameters doesn't change the default value from the AnimalSchema nor does at StorySchema.
var mongoose = require('mongoose');
var AnimalSchema = new mongoose.Schema({
name: {type : String, default: ""},
audio: {type : String, default: ""},
image: {type : String, default: ""}
});
mongoose.model('Animal', AnimalSchema);
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Animal = mongoose.model('Animal');
var Story = mongoose.model('Story');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/animals', function(req, res, next){
Animal.find(function(err, animals){
if(err){
return next(err);
}
res.json(animals);
});
});
router.post('/animals', function(req, res, next){
var animal = new Animal(req.body);
animal.save(function(err,animal){
if(err){return next(err);}
res.json(animal);
});
});
router.get('/stories', function(req, res, next){
Story.find(function(err, stories){
if(err){return next(err);}
res.json(stories);
});
});
router.post('/stories', function(req, res, next){
var story = new Story(req.body);
story.save(function(err, story){
if(err){return next(err);}
res.json(story)
});
});
module.exports = router;
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
// connect MongoDB
mongoose.connect('mongodb://localhost/stuckyToys', function(err,db){
if (!err){
console.log('Connected to /stuckyToys!');
} else{
console.dir(err); //failed to connect
}
});
require('./models/Animals');
require('./models/Stories');
var routes = require('./routes/index');
var users = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// 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;
I think I made an error in my app.js file. But not sure where it is.
Anyone knows what I did wrong?
I would do something like
{*(Model)}.findById(id, function(err, animal) {
if (err) console.log(err);
{update new values here in animal with the ones you are receiving in the request}
animal.save(function(err) {
if (err) console.log(err);
});
});

node express express.static prevents access from root path '/'

I am using express and I have a catch all route
router.use('*',function(){...});
and a root route
router.use('/', function(){...});
I have this route placed after the
app.use(express.static(path.join(__dirname, 'public')));
this causes my routes to not fire when placed below the previous line. however if I put my routes above it my catch all is also called on static asset requests. is there a way I can catch all requests except for the assets in my public folder including the route '/'? I don't want to resort to using regex and having to update it every time a directory is added to the public directory.
sorry for not being more details here are the relavant files
//app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
/* This is going to initialize the menubar for nwjs it is currently commented out as this is a non issue at this point
setTimeout(function () {
//initialize passport
var passport = require('./helpers/passport.js');
//setup routes
//setup window menu
console = window.console;
console.log(passport);
passport.init(app);
var gui = window.require('nw.gui');
var win = gui.Window.get();
var menu = new gui.Menu({
type: 'menubar'
});
menu.createMacBuiltin('jist', {
hideEdit: true,
hideWindow: true
});
gui.Window.get().menu = menu;
},1000);*/
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// 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;
//window.location.href="http://localhost:3000";
this is my index router
//routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.use('*', function(req, res, nex){
var path = req.originalPath;
if(~['/users/login', '/users/signup'].indexOf(path) || req.user) return next();
if(!req.user) return res.redirect('/users/login');
});
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;

Resources