I'm learing ExpressJS, i want to do the login part , but i gave me this
Cannot POST /login
im using the post method why it gave me this error
here a detailed post , thank you in advance for helping me
html part
<form method="POST">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" >
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password">
<button type="submit">Login</button>
</div>
</form>
The route.js
router.post('/login'),(req,res)=>{
var username= req.body.name;
var password = req.body.password;
con.query('SELECT * FROM authentication WHERE username = ?',username, function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if(results[0].password == password){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"username and password does not match"
});
}
}
else{
res.send({
"code":204,
"success":"username does not exits"
});
}
}
});
}
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
when trying to post this form i'm getting:
Cannot POST /login
what am i missing here?
You should handle current page, not '/login' page in route.js :
router.post('/', //...
Instead of writing
router.post('/login', //...
Because you sent the form data to the current page not to the '/login' page
Why current page ?
Because, you didn't define action attribute in your form
You need to define form action
<form action="/login" method="post">
But I recommend you to use js for sending requests
fetch('/login', {
method: 'POST',
body: JSON.stringify(yourFormData),
// ...another Opts if it needs
})
Also it can be problem with your server code because I don't see defining router in indexRouter file, you should add it:
const express = require('express');
const router = express.Router();
// then your code:
router.post('/login', loginController);
But you can add this line for check post requests:
app.post('/login', (req, res) => {
res.status(201).json(req.body); // or console.log
});
Related
I am trying to log in a user from a web site. I am using parse-server hosted at Microsoft Azure. I keep getting the following error, just trying to access the home page:
Error handling request: ParseError { code: 209, message: 'invalid session token' } code=209, message=invalid session token
And the browser throws a "...redirected you too many times." error. I'm not sure what I'm doing wrong, I've tried researching and piecing this together from here: https://github.com/ParsePlatform/parse-server/issues/497 with no luck.
index.js
var express...
etc...
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended:false});
//Server configuration
...
//Express configuration
var app = express();
app.use(cookieParser()); // read cookies (needed for auth)
// get information from html forms
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use('/public', express.static(__dirname + '/public'));
app.use('/parse', new ParseServer(config.server));
app.use('/parse-dashboard', ParseDashboard(config.dashboard, true));
app.use(cookieSession({
name: "COOKIE_NAME",
secret: "COOKIE_SECRET",
maxAge: 15724800000
}));
app.use(function (req, res, next) {
Parse.Cloud.httpRequest({
url: 'https://localhost:1337/parse/users/me',
headers: {
'X-Parse-Application-Id': process.env.APP_ID,
'X-Parse-REST-API-Key': process.env.API_KEY,
'X-Parse-Session-Token': req.session.token
}
}).then(function (userData) {
req.user = Parse.Object.fromJSON(userData.data);
next();
}).then(null, function () {
return res.redirect('/login');
});
});
app.use(flash()); // use connect-flash for flash messages stored in session
//routes
require('./routes/routes.js')(app);
app.listen(process.env.PORT || url.parse(config.server.serverURL).port, function () {
console.log(`Parse Server running at ${config.server.serverURL}`);
});
routes.js
// app/routes.js
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended:false});
module.exports = function(app) {
// HOME PAGE ========
app.get('/', function(req, res) {
res.render('index.ejs', { title: 'Audiomesh' }); // load the index.ejs file
});
// LOGIN ===============================
// show the login form
app.get('/login', function(req, res) {
res.render('login.ejs', { message: req.flash('loginMessage') });
});
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
req.session.user = user;
req.session.token = user.getSessionToken();
res.redirect('/dashboard');
}, function(error) {
req.session = null;
res.render('login', { flash: error.message });
});
});
// DASHBOARD =====================
app.get('/dashboard', function(req, res) {
res.render('dashboard.ejs', {
user : req.user // get the user out of session and pass to template
});
});
// LOGOUT ==============================
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
};
login.ejs
<body>
<p><%= message %></p>
<form name="loginForm" action="/login" method="post">
<label>Email</label>
<input type="email" name="email"></input>
<label>Password</label>
<input name="password" type="password"></input>
<input class="button" type="submit" value="Log In">
</form>
<p>Coming soon azure</p>
<p>Back to home page</p>
</body>
The goal of my web site is for the home page to be an advertising/landing page for the mobile app. So if you're logged in, there's no evidence here. Once you click "Login" then it would check if the user is logged in and either load their dashboard (if true), or the login page (if false).
The problem right now is I can't even load the home page. I get too many redirects.
I'm trying to implement passport.js in a Node/Express/Sequelize app. I'm trying to stay as faithful as possible to both the official documentation and the Scotch.io tutorial, and currently have the following relevant code segments in my scaffolding:
app.js
const express = require('express');
const http = require('http');
const https = require('https');
const sequelize = require('sequelize');
const db = require('./config/sequelize');
const config = require('./config/config');
const passport = require('./config/passport');
const app = express();
const port = 3000;
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
app.listen(port);
app.post('/signup', passport.authenticate('local', function(req, res, next, err){
if (err) { console.log(err); }
res.json(req.body);
}));
./config/passport.js
const db = require('./sequelize');
const passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(user, done) {
db.User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(email, password, done){
process.nextTick(function() {
db.User.findOne({ email : 'local.email' }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
}
else {
db.User.create({
username: 'local.email',
password: 'local.password'
});
}
});
});
}
));
module.exports = passport;
./views/signup.ejs
<!-- LOGIN FORM -->
<form action="/signup" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" name="username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password">
</div>
<button type="submit">Signup</button>
</form>
With this implementation in hand, I fire up the app, enter the email address and password to sign up on ./views/signup.ejs, and get the following error:
TypeError: Cannot read property 'body' of null
at C:\Users\Adam\Desktop\repos\chinese-democracy\app.js:45:15
at allFailed (C:\Users\Adam\Desktop\repos\chinese-democracy\node_modules\passport\lib\middleware\authenticate.js:94:18)
at attempt (C:\Users\Adam\Desktop\repos\chinese-democracy\node_modules\passport\lib\middleware\authenticate.js:167:28)
...
This indicates that req.body is being returned as null, and I have a suspicion it has to do with the manner in which the deserializeUser and serializeUser functions are defined in ./config/passport.js, but how can I get verbose error outputs to determine what the exact cause is? Also, I have done sanity CRUD checks with my Sequelize database so I omitted that file, but will provide it as an edit if any of you think that would be of use in resolving this issue.
Please try this in your app.js :
app.post('/signup', passport.authenticate('local'), function(req, res, next, err){
//^ close
// If this function gets called, authentication was successful.
res.redirect('/users/' + req.user.username);
});
If you need a custom callback:
app.post('/signup', function(req, res, next){
passport.authenticate('local', function(err, user, info) {
//Your code here
})(req, res, next);
});
Please refer to http://passportjs.org/docs/authenticate for more details.
I'm calling an express endpoint from after form submission in Jquery. So when the form submits, it calls signUpUser(value) which then initiates an ajax request to the express server.
The call to /signup is resulting in a 404, I thought I was setting up the endpoint properly.
Any reason it is giving a 404? I've tried GET/POST and a few other iterations.
$(document).ready(function(){
$('#signupForm').submit(function() {
console.log("here");
console.log("yup");
var value=$("#email").val();
signUpUser(value);
});
var signUpUser = function (value){
console.log("yaaa");
$.ajax({
type:"GET",
url:"/signup"
})
.done(function(){
window.location='/confirmation.html';
})
.fail(function(){
alert('An error occurred while trying to sign up. Please try again.')
});
};
});
var express = require('express');
var app = express();
var cors = require('cors');
var path = require('path');
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
var router = express.Router();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/thesis.html', function(req, res) {
res.sendFile(path.join(__dirname + '/thesis.html'));
});
app.get('/confirmation.html', function(req, res) {
res.sendFile(path.join(__dirname + '/confirmation.html'));
});
app.get('/about.html', function(req, res) {
res.sendFile(path.join(__dirname + '/about.html'));
});
app.post('/signup', function (req, res) {
$.ajax({
type:"POST",
url:"https://us11.api.mailchimp.com/3.0/lists/8085fb931b/members",
user: 'anystring:XX',
header: 'content-type: application/x-www-form-urlencoded',
data: { "email_address": "ttttt#ssssssss.com",
"status": "subscribed"
}
})
.done(function(){
window.location='/confirmation.html';
res.send(200);
})
.fail(function(){
alert('An error occurred while trying to sign up. Please try again.')
});
});
<form id="signupForm" ng-controller="formController">
<fieldset>
<input type="test" id="email" name="field1" id="field1" ng-model="email">
<input type="submit" value="Create Profile">
</fieldset>
</form>
The end point you're trying to hit, /signup, is a declared as a POST end point. The type attribute in your ajax request is GET. You're getting a 404 because you're trying to make a request to a GET end point that doesn't exist.
I am very much beginner with node.js.
There is a sample form with that I am trying to insert values in database-
Here is my test page-
<form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencoded">
<input type="text" id="username_input" name="username">
<input type="text" id="password_input" name="password">
<input type="submit" name="Submit" value="Insert" class="btn">
</form>
Trying to post it-
I created test.js file and writing post method in it-
exports.list = function (req, res) {
req.getConnection(function (err, connection) {
console.log(con)
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
});
}
But this didn't work.
I tried writing post method in main server.js file also-
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
but this didn't work also.
I am following current settings in server.js file-
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, index_form = require('./routes/index_form')
, user = require('./routes/user')
, test = require('./routes/test')
, mysql = require('mysql')
, http = require('http')
, path = require('path')
, mongoose = require('mongoose');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass#123'
});
var app =express();
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(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function () {
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/test', test.test);
app.get('/users', user.list);
app.get('/index_form', index_form.index_form)
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
Kindly guide me through this all , How do I make my form post with node.js?
Did you try putting app.post("/create", test.test); into your current server.js after your GET routes yet? Because what I saw here your current server.js does not have any POST request.
I am pretty new to Node.js development, and I am aware that there are several stack overflow questions like this already, unfortunately none seem to fix my problem. So I feel all I can do is ask my question
So I am use Node.js with Express and the Jade view engine.
I based some of my code on this article : http://howtonode.org/express-mongodb
Anyway here is what I have
The node app :
var express = require('express');
var home = require('./routes/home');
var d3demo = require('./routes/d3demo');
var PersonProvider = require('./public/javascripts/personProvider').PersonProvider;
var personProvider = new PersonProvider('localhost', 27017);
var LinkProvider = require('./public/javascripts/linkProvider').LinkProvider;
var linkProvider = new LinkProvider('localhost', 27017);
var http = require('http');
var path = require('path');
var app = express();
//=============================================================================
// EXPRESS SETUP
//=============================================================================
app.configure(function(){
app.set('port', process.env.PORT || 2000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
//app.use(require('connect').bodyParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
//=============================================================================
// ROUTING
//=============================================================================
app.get('/home', function (req, res) {
home.homeGet(req, res, commonHelper, personProvider, linkProvider);
});
app.post('/home', function (req, res) {
home.homePost(req, res, personProvider);
});
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
and this is the Home route
/*
* GET home page.
*/
exports.homeGet = function(req, res, commonHelper, personProvider, linkProvider){
commonHelper.seedData(personProvider, linkProvider, function() {
res.render('home');
});
};
exports.homePost = function (req, res, personProvider) {
var newUserEmail = req.body.email;
console.log(req.body.length);
//console.log(x);
//var email = req.param('Email');
console.log("/Home posted Email :" + newUserEmail);
personProvider.save({
//email: req.param('Email'),
email: newUserEmail,
}, function (error, docs) {
if(error == null) {
res.redirect('/d3demo');
} else {
res.render('home');
}
});
};
And this is the jade view
extends layout
block head
link(rel='stylesheet', href='/stylesheets/home.css')
script(src='/javascripts/home.js')
block content
form(method='post', id='homeForm', action='http://localhost:2000/home')
div(id='dialog', title='error', style='display:none;')
p You need to supply a valid email
div(id='NewDetailsArea')
p Enter your email address, and then click enter
| <input type="text" id="email" class="email"></input>
div#homeSubmit
input(type='submit', value='Enter', id='enterEmail')
Which gets rendered to this
<form method="post" id="homeForm" action="http://localhost:2000/home">
<div id="dialog" title="error" style="display:none;">
<p>You need to supply a valid email</p></div>
<div id="NewDetailsArea">
<p>Enter your email address, and then click enter </p>
<input type="text" id="email" class="email">
</input><div id="homeSubmit"><input type="submit" value="Enter" id="enterEmail">
</div>
</div>
</form>
So the problem:
Well the problem is actually pretty simply. Within the function
homePost = function (req, res, personProvider)
I would like to be able to get the value of the 'email' form field
I have tried req.param('email'), req.body.email I have tried the standard express.bodyParser() and also the connect (which someone mentioned in another answer) one require('connect').bodyParser(), but alas all I get is undefined.
Also if I try and console.log(req.body) I get undefined
What am I doing wrong?
You need to supply a name attribute for the email input. The name is what gets sent when the form is submitted:
<input type="text" id="email" name="email" class="email">