using simple node app, localhost not sending data - javascript

I'm a newbie so be kind. I've been trying to learn passport via an online tutorial (this one, github here) and as far as I can tell I've recreated the code verbatim but I'm getting an error that the localhost didn't send any data. My full code is here. I'm pasting some code below but I'm honestly unsure which piece of code to post since I don't know where the error is occurring.
Here's the server app:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
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('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
//Init app
var app = express();
//View engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
//body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
//set static folder
app.use(express.static(path.join(__dirname, 'public')));
//express session middleware
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//passport init
app.use(passport.initialize());
app.use(passport.session());
//validator middleware-- this code is straight from the validator github page
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split(',')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
//connect flash middleware
app.use(flash());
//global variables for flash messages
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
//set port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function() {
console.log('Server started on port ' + app.get('port'));
});
Here's the form:
<h2 class="page-header">Register</h2>
<form method="post" action="/users/register">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" placeholder="Email" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" placeholder="Password" name="password2">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
And here's the user js:
var express = require('express');
var router = express.Router();
//register
router.get('/register', function(req, res) {
res.render('register');
});
//login
router.get('/login', function(req, res) {
res.render('login');
});
//register user
router.post('/register', function(req, res) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
});
module.exports = router;

First things first: you are actually not doing anything on the post('/register'..)
You should save your model and return it if successful, something like this:
var schema = new mongoose.Schema({ name: 'string', email: 'string' });
var User = mongoose.model('User', schema);
//register user
router.post('/register', function(req, res) {
var name = req.body.name;
var email = req.body.email;
var user = new User({ name: name, email: email});
user.save(function (err) {
if (err) throw err;
res.send(user);
});
});
Of course you would define your model on a separate folder and import it to where it fits.

Related

invalid csrf token express

I'm learning about backend and I have a problem with csurf protection in my express nodejs project. When I submit in add-admin form is working find, but add-product form and edit-product form I receive the error
invalid csrf token
403
ForbiddenError: invalid csrf token
this is my app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
const Product = require('./models/product');
var app = express();
mongoose.connect('mongodb://localhost:27017/project3', {useNewUrlParser: true, useUnifiedTopology: true});
require('./config/passport')(passport);
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout:'layout', extname:'.hbs', runtimeOptions: {
allowProtoPropertiesByDefault: true,
allowProtoMethodsByDefault: true
}}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret:'mysupersecret',
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection}),
cookie: {maxAge: 30*60*24*60*1000}
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/static',express.static('public'));
app.use(function(req,res,next){
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
//routes
app.use('/admin', adminRouter);
app.use('/user', userRouter);
app.use('/', indexRouter);
// 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;
My admin.js
var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var multer = require('multer');
var mongoose = require('mongoose');
var async = require('async');
var {check, validationResult} = require('express-validator');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var csrfProtection = csrf();
router.use(csrfProtection);
mongoose.connect('mongodb://localhost:27017/project3', {useNewUrlParser: true, useUnifiedTopology: true});
var Product = require('../models/product');
var User = require("../models/user");
// add-product page
router.get("/add-product",csrfProtection,
function(req,res,next) {
var messages = req.flash('error');
res.render('admin/add-product', {
csrfToken: req.csrfToken(),
messages: messages,
hasErrors: messages.length>0,
});
});
//edit-product page
router.get("/edit-product/:id", csrfProtection,function(req,res,next){
Product.findById(req.params.id, function(err, data){
if(err) {
throw err;
} else {
res.render("admin/edit-product", {
csrfToken: req.csrfToken(),
editedProduct:data,
});
}
});
});
//delete a product
router.get("/delete-product/:id", function(req,res,next){
Product.deleteOne({_id: req.params.id}, function(err){
if(err) {
throw err;
} else {
res.redirect("../list-product");
}
});
});
//list admin
router.get('/list-admin', function(req,res,next){
User.find({rule: 2}, function(err,admin){
if(err) {
throw err;
}
else {
res.render('admin/list-admin', {
csrfToken: req.csrfToken(),
admin: admin
});
}
});
});
// add account admin
router.get('/add-admin', function(req,res, next) {
var messages = req.flash('error');
res.render('admin/add-admin', {
csrfToken: req.csrfToken(),
messages: messages,
hasErrors: messages.length>0
});
});
module.exports = router;
my add-user.hbs
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offet-3">
<form action="/admin/add-product" method="post" id='checkout-form' enctype="multipart/form-data">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="name">Tên sản phẩm</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
</div>
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-success">Thêm sản phẩm</button>
</form>
</div>
</div>
edit-product.hbs
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offet-3">
<form action="../edit" method="post" id='edit-form' enctype="multipart/form-data" >
<div class="row">
<input type="hidden" name="IDChar" value={{editedProduct._id}}>>
<div class="col-xs-12">
<div class="form-group">
<label for="name">Tên sản phẩm</label>
<input type="text" id="name" value="{{editedProduct.name}}" class="form-control" required>
</div>
</div>
<hr>
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-success">Thay đổi</button>
</form>
</div>
</div>
add-admin.hbs
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h3>Thêm tài khoản admin</h3>
{{#if hasErrors}}
<div class="alert alert-danger">
{{#each messages}}
<p>{{this}}</p>
{{/each}}
</div>
{{/if}}
<form action="/admin/add-admin" method='post'>
<div class="form-group">
<label for="email">Email</label>
<input type="text" id ="email" name = "email" class="form-control">
</div>
<div class="form-group">
<label for="password">Mật khẩu</label>
<input type="password" id="password" name="password" class="form-control">
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit"class="btn btn-primary">Thêm tài khoản Admin</button>
</form>
</div>
</div>
i searched in google and document of csurf but i can't find resolve. Please help me, thank you for watching.

App.post from EJS form not working - ExpressJS

I am using the express framework with EJS as the view engine. I have some basic routes ('/' & '/users') in the application. I also have a form in my EJS page which I'm using the users to login. Here I have form with action="/login" and method="POST". And I have created a handler function app.post in the app.js to check credentials and redirect to users page.
But when I click submit button of the page express app saying that "/login" not found. Below is the directory structure of the entire app.
menu.ejs:
<form method="POST" action="/login">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="login" class="login loginmodal-submit" value="Login">
</form>
And the 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 session = require('express-session');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var path = require('path');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var app = express();
// 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);
app.use('/login', loginRouter);
// 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');
});
//express session
app.use(session({
secret:'secret_key',
resave:true,
saveUninitialized:true
}));
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
mysql
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'secret_pw',
database:'my_db'
});
//login authentication
app.post('/login', function(req,res){
var username = req.body.username;
var password = req.body.password;
if(username && password){
connection.query('SELECT username,password FROM logindetails WHERE username = ? AND password = ?',[username,password], function(error,results,fields){
if(results.length > 0){
req.session.loggedin = true;
req.session.username = username;
res.redirect('/users');
} else{
res.send('Incorrect username and password');
}
res.end();
});
}
else{
res.send('Please enter username and password');
res.end();
}
});
module.exports = app;
And the login route is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { page:'home', menuId:'home' });
});
module.exports = router;
Omit this code from app.js
app.post('/login', function(req,res){
/....../
});
Then add this to login-router
router.post('/', function(req, res) {
/......../
});
Because your app reach this block below before executing app.post
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
Move the following block below app.post.
Also, you should initialise bodyParser and session before initialising routes.

Form inputs not retrievable using bodyParser and Router()

I am trying to create a registration form which will pass data to the registration route. However, I am having trouble retrieve the form inputs in registration route. Please advice how to retrieve the form data inside the api.js file. I have tried using POSTMAN to send data to the /api/registration endpoint which did create a user in the database. When I actually use the html form to register, it failed.
HTML
<!DOCTYPE html>
<html>
<body>
<form action="/api/register" enctype="multipart/form-data" method="post">
<input name="email" type="text" placeholder="Email">
<input name="password" type="password" placeholder="Password">
<input name="passwordConf" type="password" placeholder="Confirm Password">
<input type="submit" value="Register">
</form>
</body>
</html>
Index.js
//----setting up modules
const express = require('express');
const hbs = require('hbs');
const path = require('path');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/test');
//----define port connection on various environmentls
const port = process.env.PORT || 3000;
//----createing express app
var app = express();
// parse incoming requests
app.use(bodyParser.json());
//----use express middle-ware to utitlize public folder
// app.use(express.static(__dirname + 'public'));
app.use('/public', express.static(path.join(__dirname,'public')));
//see the first argument in above line it assigns which directory path is used to access the public file through URL
//----initializing handlebars as express view engine
app.set('view engine', 'hbs');
//----define handlebars partials and helpers
hbs.registerPartials(__dirname + '/views/partials');
//----define helper to get current year
hbs.registerHelper('getDate', ()=>{
return new Date().getFullYear();
});
//----define routes
app.get('/', function (req, res) {
res.render('home.hbs')
})
// include routes
app.use('/api', require('./routes/api'));
app.use('/', require('./routes/page'));
//----connecting to port
app.listen(port,()=>{
console.log(`success connection to port ${port}`);
})
Api.js Route
var express = require('express');
var router = express.Router();
var {User} = require('./../models/user');
var {authenticate} = require('./../middleware/authenticate');
var _ = require('lodash');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
router.post('/register',function (req, res) {
console.log(req.body);
});
module.exports = router;
pages.js
var express = require('express');
var router = express.Router();
router.get('/register', function (req, res) {
res.render('register.hbs', {title:"REGISTER"} )
})
router.get('/login', function (req, res) {
res.render('login.hbs', {title:"LOGIN"} )
})
module.exports = router;
Here is my recommendation:
Create a file called routes.js and include ALL your routes there and import it.
var express = require('express');
var router = express.Router();
app.get('/', function (req, res) {
res.render('home.hbs')
})
router.get('/api/register', function (req, res) {
res.render('register.hbs', {title:"REGISTER"} )
})
router.post('/api/register',function (req, res) {
//do your post logic here
console.log(req.body);
});
router.get('/login', function (req, res) {
res.render('login.hbs', {title:"LOGIN"} )
})
module.exports = router;
in your Index.js :
//Make sure the route is correct
app.use('/', require('/routes/routes.js'));
Doing this, I expect the error to be solved,
Good luck!

Express.js route not found

I am getting odd behavior for the route modules in this simple express app.
The root page '/' works but I am getting a 'not found' error for '/login'. But it works when I do app.get('/login', auth), instead of app.use('/login', auth). Any help is appreciated!
app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000
const path = require("path");
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const auth = require('./routes/auth');
const index = require('./routes/index');
mongoose.connect("mongodb://localhost/dev");
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use('/login', auth);
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
const 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', { res : res });
});
app.listen(port);
./routes/index
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('index');
});
module.exports = router;
./routes/auth
var express = require('express');
var router = express.Router();
router.get('/login', function (req, res, next) {
res.send('Hello world');
});
router.post('/login', function (req, res, next) {
res.send('Goodbye world');
});
module.exports = router;
./views/index.ejs
<h1>Welcome To Our App</h1>
Login
Signup
./views/login.ejs
<h1>Login</h1>
<form action="/login" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
In /routes/auth.js do router.get('/') instead of router.get('/login').
Otherwise, you would have to call localhost/login/login.

Nodejs : callback is not a function

In the below code , I am authenticating username and password user enters with the details from my mongo database . If successful , redirect to /main route (index.ejs) . I am getting error :- callback is not a function .
I am new to nodejs . I can't figure out where and why I am getting this error .
app.js
var express = require('express');
var app = 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 urlencoder = bodyParser.urlencoded({extended : true});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://<username>: <password>#ds141434.mlab.com:41434/teacherspro'; // using mLab
app.set('view engine' , 'ejs'); // ejs as view engine
var index = require('./routes/index'); // providing routes
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/main', index);
app.use('/users', users);
app.get('/login' , function(req,res,next){ // rendering homepage
console.log('\r');
res.render('login'); // rendering login.ejs
console.log('rendered master page!');
next();
});
MongoClient.connect(url , function(err,db){
if (err) return;
app.post('/login' , urlencoder , function(req,res,next){
app.use(bodyParser.json());
var UserName = req.body.UserName;
var Password = req.body.Password;
db.collection('project1').find({ '$and' : [ {"UserName" : UserName} , {"Password" : Password} ]} , {_id : 0}).forEach(function(pes){ // authenticating username and password
if(true)
{
console.log(pes);
res.redirect('/main');
}
});
});
db.close();
next();
});
app.listen(5050);
module.exports = app;
Index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
MongoClient.connect(url , function(err,db){
if (err) return;
db.collection('project1').find({"UserName" : "karan"} , {_id : 0}).forEach(function(pes){
console.log(pes);
res.render('index', {Name : pes});
});
});
});
module.exports = router;
login.ejs
<form id = 'login' method = POST action = '/login'>
<label for = 'Username'> UserName </label>
<input type = 'text' name = 'UserName' value = ''>
<br />
<label for = 'Password'> Password </label>
<input type = 'password' name = 'Password' value = ''>
<br />
<center> <input type ="submit" value = "submit" /> </center>
<br />
</form>
Post callback has the following form:
app.post(path, callback);
Check the docs. app.post
Just remove urlencoder param.

Categories

Resources