I found that the 400 HTTP error is something with syntax but I cannot find anything wrong with my syntax, could someone help take a look at it?
<!- My form view-->
<h3>Login</h3>
<form action="/home/login" method="post">
Enter your usernmae: <input type="text" name="user" value=""><br>
Enter your password: <input type="password" name="pwd" value=""><br>
<input type="submit" name="enter" value="Enter">
</form>
//controller added to my app.js
app.use('/home', indexController);
//in router.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
router.post('/login', passport.authenticate('local'), function(req, res) {
req.session.save(function (err) {
if (err) {
return next(err);
}
res.redirect('/home/' + req.user.user);
});
});
Related
So I installed body parser via
npm i install express body-parser
and I wrote a simple code designed to input a user into an array after they complete a registration form.
but when I console.log the user it returns undefined for both email and password
here is the server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const PORT = 3000;
var Users = [{"email":"mike#gmail.com", "password":"456"}];
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/Register.ejs', (req, res) => {
res.render('Register.ejs')
})
app.post('/views/Register.ejs', (req, res) =>
{
const newUser = {
email: req.body.email,
password: req.body.password
};
Users.push(newUser);
res.json(req.body.email);
console.log(Users)
}
)
app.listen(PORT);
here is the html for the register page
<h1>Please Register</h1>
<body>
<form action="/views/Register.ejs" method="POST">
<div class="div">
<label for="email">Enter Email</label>
<input type="email" id="email"for="email" id="email" required>
</div>
<div class="div">
<label for="password">Enter new password</label>
<input type="password" for="password" id="password" required>
</div>
<button type="submit"> Register </button>
</form>
</body>
Only installing body-parser is not enough. You have to put them in the code as middleware.
Top of the code use:
var bodyParser = require('body-parser');
and then use the code in somewhere middle of the code:
app.use(bodyParser.json())
I am learning passportjs and i have the following code in my server.js,the problem i am facing is that the passport.use('local',new LocalStrategy({}) in the below code is never called,the rest is working fine except for the localstrategy,been strugling with this for hours!!
I am learning passportjs and i have the following code in my server.js,the problem i am facing is that the passport.use('local',new LocalStrategy({}) in the below code is never called,the rest is working fine except for the localstrategy,been strugling with this for hours!!
const express=require("express");
const bodyParser=require('body-parser');
const ejs=require("ejs");
const cookieParser=require('cookie-parser');
const passport=require('passport');
const LocalStrategy=require('passport-local').Strategy;
const session=require("express-session");
const app=express();
app.set(express.static,'public');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret:'library'}));
app.use(passport.initialize());
app.use(passport.session());
app.post('/auth/signUp',(req,res,next)=>{
console.log('body',req.body)
passport.authenticate('local',(err,user,info)=>{
console.log("whattt",user)
req.login(user,(err)=>{
res.redirect('/auth/profile');
});
})(req, res, next);
});
app.get('/auth/profile',(req,res)=>{
res.json(req.user);
});
app.get("/",async (req,res)=>{
res.render('index.ejs');
});
passport.serializeUser((user,done)=>{
done(null,user.id);
});
passport.deserializeUser((id, done)=> {
console.log("id",id);
let data=[{id:1,name:"malouda"},{id:2,name:"Jason"}];
let user = data.find((obj)=>{ return obj.id === id; });
done(null,user);
});
passport.use('local',new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},(username,password,done)=>{
user={id:1,name:"malouda"};
console.log("LocalStrategy")
done(null,user);
}));
app.listen(3000,()=>{
console.log("Listening on port 6000");
});
and in my index.js i have the following form
<form name="signUpForm" action="/auth/signUp" method="post" multipart='urlencoded'>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name="password " id="exampleInputPassword1" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Passport LocalStrategy is used for login authentication.
In Signup, you don't need the passport. In Signup, you just create the user by storing it in the database.
You need to add
Passport.authenticate(`local`, (err, user, info) => {}
In your login API to authenticate the user.
As the name suggests, Passport.authenticate authenticates the user credentials. SO first you need to create the user.
Read more here.
Hope I cleared your thoughts.
In 'app.js' I have
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
'index.js' full codes
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Here' });
});
router.post('/manager', function(req, res, next) {
var connection = mysql.createConnection({
host : 'localhost',
user : req.body.username,
password : req.body.password,
database : 'shops'
});
connection.connect(function(err){
if(!err)
res.render('manager', { title: 'Here' });
else
console.log("Error connecting database ...");
});
});
module.exports = router;
In 'index.html' login form
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' type='text'><br>
Password<br>
<input id='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>
In index.js line 12-13
req.body.username
req.body.password
Everytime I try to parse data from html form, they return 'undefined'. I'm new to node.js scripting. Am I doing something wrong?
You're missing name attributes on your <input> tags. Add them like:
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' name='username' type='text'><br>
Password<br>
<input id='password' name='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>
I am trying to store some user information in a MongoDB database.
From the front-end (AngularJS) on localhost:9000 I make a POST to the backend (express on localhost:3000)
I'm getting in the header information all the data, including the email-address.
but in the body email is undefined??
Console from Node server:
Console from Web browser:
I must do something wrong with the body parser?
Front-end:
registration View:
<form ng-submit="submit()" name="register" class="form-signin" novalidate>
<h1 class="form-signin-heading text-muted">Register</h1>
<input name="email" ng-model="email" type="email" class="form-control" placeholder="Email address" required autofocus="" required>
<p class="help-block" ng-show="register.email.$dirty && register.email.$invalid">Please enter a proper email.</p>
<input name="password" ng-model="password" type="password" class="form-control" placeholder="Password" required>
<input name="password_confirm" ng-model="password_confirm" type="password" class="form-control" placeholder="Confirm Password" validate-equals='password' required>
<p class="help-block" ng-show="register.password_confirm.$dirty && register.password_confirm.$invalid">please match the password.</p>
<button ng-disabled="register.$invalid" class="btn btn-lg btn-primary btn-block" type="submit">
Submit
</button>
</form>
Front-end controller:
'use strict';
angular.module('app')
.controller('RegisterCtrl', function ($scope, $http, alert) {
$scope.submit = function() {
var url = 'http://localhost:3000/register';
var user = {
email: $scope.email,
password: $scope.password
};
$http.post(url, user)
.success(function(res){
alert('success', 'OK!', 'You are now registered');
})
.error(function(err) {
alert('warning', 'Opps!', 'Could not register');
});
}
});
Back-end NodeJS express server.
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(bodyParser.json());
//Verbind front-end met backend
app.use(function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
})
//MongoDB userModel
var User = mongoose.model('User', {
email: String,
password: String
});
//Reactie op de FRONT END POST voor REGISTRATIE
app.post('/register', function(req, res){
//emailVerification.s end(req.user.email);
//createSendToken(req.user, res);
var user = req.body;
console.log('req.body**' + req.body);
console.log('req.headers**' +req.headers);
var newUser = new User({
email: user.name,
password: user.password
})
newUser.save(function(err) {
//als goed opgeslagen > send status 200 en json new user
res.status(200).json(newUser);
console.log(newUser);
});
});
//MONGODB CONNECTIE =====================================
mongoose.connect('mongodb://....');
//MONGODB CONNECTIE =====================================
var server = app.listen(3000, function(){
console.log('api listening on ', server.address().port);
})
Thanks for your help.
Try using Dot operator , Change your Template as below,(sample code)
<form class="list" name="loginForm" ng-submit="login(credentials)" novalidate>
<label class="item item-input item-floating-label" for="username">
<span class="input-label">UserName</span>
<input type="text" placeholder="Username" id="username" ng-model="credentials.username">
</label>
<label class="item item-input item-floating-label" for="password">
<span class="input-label">Password</span>
<input type="password" placeholder="password" id="password" ng-model="credentials.password">
</label>
<button class="button button-block button-dark activated" type="submit">Logga in</button>
</form>
And in your Controller,
you get username as
var user = $scope.username;
Please read upon this article about Understanding Scopes
https://github.com/angular/angular.js/wiki/Understanding-Scopes#ngRepeat
Happy Coding
I made a typo in "Back-end NodeJS express server"
var newUser = new User({
email: **user.name,**
password: user.password
})
must be:
var newUser = new User({
email: **user.email,**
password: user.password
})
I'd like to know if it's possible to rewrite an url with express.
I actually have this code :
var http, express, app;
http = require("http");
express = require("express");
app = express();
app.use(express.json())
app.use(express.urlencoded())
.post("/ajax_login", function (req, res) {
"use strict";
http.get({ host: "localhost", port: 8080, path: "/users/" + req.body.email + "/email" }, function (resp) {
resp.setEncoding("utf8");
resp.on("data", function (data) {
json = JSON.parse(data);
if (json.password.password === sha1(req.body.password)) {
res.render("home.ejs");
} else {
res.render("login.ejs", { email : req.body.email, error : "password is not good" });
}
});
});
})
.get("/login", function (req, res) {
"use strict";
res.render("login.ejs");
})
.listen(3030);
I call /ajax_login from a form :
<form method="post" action="/ajax_login">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" />
</div>
<button type="submit" class="btn btn-primary">Connection</button>
</form>
The problem is : when I call /ajax_login, after res.render my HTML code on my browser is changed, but the url still /ajax_login.
How I can change this URL ?
I know the javascript solution :
window.history.pushState("", document.title, "/login");
But, I'd like to know if a solution exist from the server.
Thanks
I would add an error to the request locals, redirect to login, and then check if an error exists when rendering the login page.
.post("/ajax_login", function (req, res) {
"use strict";
...
if (password && email IS OK) {
res.locals.errorMSG = "password is not good";
res.redirect("/login"); //redirect vs render
} else {
res.render("home.ejs");
}
})
.get("/login", function (req, res) {
"use strict";
res.render("login.ejs", {error: res.locals.errorMSG || null});
})
res.locals
res.redirect