Using express 3.1.0 I have a super simple form:
<form action="/signup" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div><input type="submit" value="Sign Up"/></div>
</form>
and in the app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, User = require('./models/User.js')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/form', function(req, res) {
fs.readFile('./form.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
});
app.post('/signup', function(req, res) {
var username = req.body.username;
var password = req.body.password;
User.addUser(username, password, function(err, user) {
if (err) throw err;
res.redirect('/form');
});
});
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
when trying to post this form i'm getting:
Cannot POST /signup
and in the console:
"NetworkError: 404 Not Found - http://localhost:3000/signup"
what am i missing here?
Your example works for me. I removed the references to User, user, and routes so that I can run it and the HTTP POST is received and displayed correctly in the console.
app.post('/signup', function(req, res) {
var username = req.body.username;
var password = req.body.password;
console.log("post received: %s %s", username, password);
});
I suspect the error is in your User.addUser() code.
router.route('/signup')
// (accessed at POST http://localhost:3000/api/signup)
.post(function(req, res) {
var username = req.body.username;
var password = req.body.password;
res.json(
{
message: 'signup success',
username : username,
password : password,
}
);
})
.get(function(req,res){
res.json({message: 'get request from signup'});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
You can write something like this:
action="http://localhost:3000/sin"
Related
When I send a request to my server I have no problem, but when I POST I run into a server timeout. (2 minutes by default, but if I add server.setTimeout(15000) I get a 15 second delay.) Once the server times out the process completes as expected. Interestingly, if I add a console.log(res) before the res.finished || next() the delay goes away.
post.html:
<form action="http://localhost:3000" method="post">
<input type="text" name="user[name]">
<input type="text" name="user[email]">
<input type="submit" value="Submit">
</form>
test.js:
'use strict'
var express = require('express')
var app = express()
var server = require('http').createServer(app)
//server.setTimeout(15000);
const bodyParser = require("body-parser");
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi')
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: true
})
nodeSSPIObj.authenticate(req, res, function(err){
//console.log(res);
res.finished || next()
})
})
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post("/", function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<html>");
res.write("<body>");
res.write("<h1>My Header</h1>");
res.write("<p>My paragraph.</p>");
res.write("<p>Name = " + req.body.user.name + "</p>");
res.write("<p>Email = " + req.body.user.email + "</p>");
res.write("</body>");
res.write("</html>");
res.end();
console.log('End post');
});
// Start server
var port = process.env.PORT || 3000
server.listen(port, function () {
console.log('Express server listening on port %d in %s mode', port, app.get('env'))
})
It turns out the problem went away when I reordered the routing to put the bodyParser lines above the nodeSSPI check.
Specifically, I moved these lines:
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
Above:
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi');
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: false
});
nodeSSPIObj.authenticate(req, res, function(err){
res.finished || next();
});
});
I'm sure this has already been answered but I can't find the exact question I'm looking for.
I have an ejs file that has this for the form.
<form action="" method="POST">
<div class="input-group">
<input type="text" class="form-control" name="userSearchInput" placeholder="Enter the id of the product you would like to buy" aria-label="Recipient's username" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="searchBTN" type="submit"><i class="fas fa-cart-plus mr-2"></i>Add to Cart</button>
</div>
</div>
</form>
On the node side in my app.js file, I've installed and downloaded both express and body-parser and done the requisite require function.
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
I've set up my middleware for body-parser here:
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Then, to get the content of what the user types into the input text box, I'm using this:
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
This is my first time using app.post and since nothing is being console logged- I'm not sure where I'm going wrong.
full app.js file
var express = require('express');
var path = require('path');
var http = require('http');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var nodemon = require('nodemon');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// create connection to mySQL db
var connection = mysql.createConnection ({
host : 'localhost',
user : 'root',
password : 'root',
database : 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
app.get('/', function(req, res){
res.render('index', {list: results});
})
});
app.post('/', function(req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});
use
<form action="/" method="post">
Firstly add form action in your ejs file like action="/search".Step 2: try with app.post('/search'
Works fine i just commented out db connections only.
may be try this app.js file with new express project.
Run command node app instant of npm start
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
// var nodemon = require('nodemon');
// var mysql = require('mysql');
var app = express();
var port = process.env.PORT || 3000;
// setting up views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// middleware for bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/*
create connection to mySQL db
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'bamazon'
});
// initialize connection
connection.connect();
// run db query and print items to index html home page
connection.query('SELECT * from products', function (error, results) {
if (error) throw error;
console.log(results);
});
*/
app.get('/', function (req, res) {
res.render('index', { list: [], title:"salman" });
})
app.post('/', function (req, res) {
var item = req.body.userSearchInput;
console.log(item);
});
// setting up listen for server function
app.listen(port, function (err) {
if (err) throw err;
console.log("Server is running on port " + port);
});
Hello i am trying to do a simple log in system without(password) in nodejs and expressjs, using sessions. My problem is that when I try to print the log in name on to the next page it dosent come out.
login html:
<form method="post">
<label for="">UserName:</label>
<input type="text" name="username" placeholder="Enter username" >
<input type="Submit" value="Submit">
</form>
main.html:
<h3> Welcome: <%= user %> </h3>
index.js:
var express = require('express');
var jokes = require('../model/jokes');
var session = require("express-session")
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('main', { title: 'Express', user: session.loggedin });
})
router.get('/login',function(req,res){
res.render('login');
})
router.get('/joke', function(req,res){
res.render('randomJoke',{ jokesObj : jokes.getRandomJoke()});
})
router.get('/allJokes', function(req,res){
res.render('Jokes',{ jokesObj1: jokes.allJokes});
})
router.get('/addNewJoke', function(req,res){
res.render('addJokes');
})
router.post('/storeJoke', function(req,res){
var funJoke = req.body;
var jsonJoke = JSON.stringify(funJoke);
jokes.addJoke(jsonJoke);
res.redirect('/addNewJoke');
})
module.exports = router;
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 session = require("express-session");
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
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(session({secret:'secret_3162735',saveUninitialized:true, resave: true}));
app.use('/', routes);
app.use('/users', users);
app.use(function (req,res,next) {
var usernameLogged = req.session.loggedin;
var inputName = req.body.username;
if(usernameLogged){
return next();.
}else if(inputName){
usernameLogged = inputName;
session.userName = req.body.username;
return res.redirect("/");
}else{
req.url = "/login";
return next();
}
});
// error handlers
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
So in main.html i cant se the user, i tried to print the session(usernameLogged) out in my main.html does not work.
As far as I can see it looks like your using middleware in a way it's not really supposed to be used. Middleware in Express is normally used to do an action for every (or a sub-section) of requests e.g logging, setting custom headers and so on, you can read more about Express-middleware from the documentation.
You need to have a route to respond to POST requests (which your login form should send):
Firstly, your login template needs to send the form input to /login like so:
<form method="post" action="/login">
<label for="">UserName:</label>
<input type="text" name="username" placeholder="Enter username" >
<input type="Submit" value="Submit">
</form>
To display the form you have a route like so to simply render the login template:
router.get('/login', function(req, res) {
// Show the login form
res.render('login');
})
Finally, you should have a route to accept the user-input from the form. As the form sends a POST request, you need to use router.post:
router.post('/login', function(req, res) {
if (req.session.loggedin) {
// User is already logged in, send them to the main page
return res.redirect('/')
}
else if (req.body.username) {
// User is not logged in, set the username for the user's session
req.session.userName = req.body.username;
// Then redirect to the main page
return res.redirect('/')
}
else {
// No username was entered
res.send('Please enter a username')
}
})
And finally,
You then should be safe to delete your middleware (the app.use section) of your app.js file.
Edit:
A user correctly spotted that questions (and answers) were using session rather than using req.session - Session refers to the express-session module, whereas req.session refers to the user's session.
So your '/' route should look like this:
res.render('main', { title: 'Express', user: req.session.loggedin });
If you want to show if the user is logged in or not.
Or you can do the following to show the current user's username.
res.render('main', { title: 'Express', user: req.session.userName });
So I'm stuck as to why this isn't working. Whenever I use the cookie for maxAge, it just doesn't allow me to login. It redirects me to /, so the callback is working but the session data is lost for some reason. Can anybody assist me?
Thanks in advance.
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var login = require('./routes/login');
var register = require('./routes/register');
var http = require('http');
var path = require('path');
var MongoClient = require('mongodb');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var app = express();
// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.session({
secret: '1234567890QWERT',
cookie: {maxAge: 30}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
var dbc;
var User;
MongoClient.connect('mongodb://127.0.0.1:27017/redacted', function(err, db) {
dbc = db;
User = dbc.collection('users');
});
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ email: username }, function(err, user) {
if (password == user.password) {
console.log("Login success!");
// Allows us to keep a log of when the user logs in in:
// user['loggedin'][]
// db.users.update({email: ""}, { $push : {loggedin: new Date()} } )
if(!err) done(null, user );
}
else done(err, null)
});
}
));
passport.serializeUser(function(user, done) {
done(null, {
id: user["_id"],
name: user["name"],
email: user["email"],
registered: user["registered"],
password: user["password"]
});
});
passport.deserializeUser(function(id, done) {
console.log(id);
User.find({_id: id._id}, function(err, user) {
done(err, user);
});
});
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
// User stuff
app.get('/login', login.get);
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login?m=fail'
})
);
app.get('/register', register.get);
app.post('/register', register.post);
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Your session cookie is set to last 30ms.
Per Express documentation, maxAge sets the expiration date of the cookie in ms.
Change cookie: {maxAge: 30} to something like cookie: {maxAge: 24*60*60*1000} for a longer-lasting session cookie.
I'm working with the new messages system in express 3 and figured this problem, when handling and validating forms. When submitting an invalid form, the submission fails, but there are no error messages displayed. When submitting it again, the error messages from the last request are shown. I tried using local sessions and Redis sessions, it's always the same. This is default express project:
app.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
app.response.message = function(type, msg){
// reference `req.session` via the `this.req` reference
var sess = this.req.session;
// simply add the msg to an array for later
sess.messages = sess.messages || [];
sess.messages.push({type: type, msg: msg});
return this;
};
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
console.log('req.session', req.session.messages);
var msgs = req.session.messages || [];
res.locals({
messages: msgs,
hasMessages: !! msgs.length
});
req.session.messages = [];
next();
});
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('*', function(req, res, next) {
res.message('hello', req.url);
next();
});
app.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
app.get('/hello', function(req, res) {
res.render('index', { title: 'Express' });
});
app.get('/world', function(req, res) {
res.render('index', { title: 'Express' });
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
index body addition:
<% if (hasMessages) { %>
<ul id="messages">
<% messages.forEach(function(msg){ %>
<li class="<%= msg.type %>"><%= msg.msg %></li>
<% }) %>
</ul>
<% } %>
/ there is no message
/hello shows '/'
/world shows '/hello'
reload shows '/world'
What's the problem here?
If you dont want to defer them you don't need to use sessions at all, that's the whole point in this case is to defer messages for the next render. By the time that middleware populates the "messages" and "hasMessages" it really doesn't have any unless the previous request populated them. This is typically used to defer msgs like "updated user successfully"