simple login node.js+mongoDB Cannot POST/ login - javascript

I have some problems to get a login for my webpage.
I have a user in my DB with email: peru#hotmail.com and pass 123.
the problem is that when I make the POST method it returns me the next error:
*Cannot POST /login*
this is my app.js:
var mongoose = require('mongoose');
var express = require('express');
var app=express();
var bodyParser = require('body-parser');
mongoose.connect("mongodb://localhost/myDB");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var userSchema = {
email:String,
pass:String
};
var Usuario = mongoose.model("Usuario",userSchema);
app.use(express.static("public"));
app.get("/",function(solicitud,respuesta){
respuesta.sendFile('.../prueba.html');
});
app.post("/login",function(require,respuesta){
var email = require.body.email;
var pass = require.body.pass;
console.log("post received: %s %s", email, pass);
User.findOne({email: email, pass: pass}, function(err,user){
if(err){
console.log(err);
}
respuesta.sendFile('.../work.html');
});
});
app.listen(3000);
and now this is my prueba.html:
<html>
<head>
<title></title>
</head>
<body>
<!--div class="col-md-5 center-block no float top-pace text-left"-->
<form method="post" action="/login" >
<input type="text" name="email">
<input type="text" name="pass" >
<button type="submit" >login </button>
</form>
</body>
</html>

You created model as Usuario and using User in your POST request, try changing it to Usuario, as follows:
app.post("/login",function(require,respuesta){
var email = require.body.email;
var pass = require.body.pass;
console.log("post received: %s %s", email, pass);
Usuario.findOne({email: email, pass: pass}, function(err,user){
if(err){
console.log(err);
}
respuesta.sendFile('.../work.html');
});
});

Related

Express NodeJS: Append text / <p> element to a HTML file in POST

I am trying to make a basic login system using Express, where if the user's username and password are correct according to a MySQL database, it adds a short "Success!" or "Failure" message to the bottom of the page when it receives a POST request.
I've tried using res.write("<p>Success!</p>") and res.send("<p>Success!</p>"), but neither have worked - instead they just create a new page with "Success!".
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form id="contact-form" method="POST" action="/login">
<label for="Username">Username: </label>
<input name="Username" maxlength="45"><br><br>
<label for="Password">Password: </label>
<input name="Password" type="password" maxlength="45"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
JS:
const port = 3000;
const express = require("express");
const mysql = require("mysql2");
const app = express();
const bodyParser = require("body-parser");
var conn = mysql.createConnection({
host: "localhost",
database: "database",
user: "<Username>",
password: "<Password>"
});
conn.connect((err) => {
if(err) throw err;
console.log("Connected to database.");
})
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({
extended: false
}));
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/Login.html");
});
app.post("/login", (req,res) => {
let form = req.body;
let sqlQuery = "SELECT * FROM logins WHERE Username = '" + form.Username + "' AND Password = '" + form.Password + "';";
conn.query(sqlQuery, (err, result, fields) => {
if(err) throw err;
if(result.length == 1) {
res.write("<p>Success!</p>")
} else {
res.write("<p>Failure.</p>")
}
})
});
app.listen(port);
So, how could I append a short p element / text to the bottom of an HTML file?
Okay,
So when the submit button in the login form is hit, it creates a totally new request and the old page is no longer in the context of request.
So, res.write() creates a new page, since a new request is generated.
If you want to append the failure and success messages on the same page, you can use ajax request instead of default form submission.
Send the ajax request, you will receive the response without a page reload, and then upon receiving the response, using javascript, you can append a new element with message from the server
const contactForm = document.getElementById('contact-form');
contactForm.addEventListener('submit',(e)=>{
e.preventDefault();
const username = contactForm.elements['username'].value;
const password = contactForm.elements['password'].value;
// now make the ajax call, you can use any library like FetchAPI, axios or even jQuery Ajax
fetch('http://backend/endpoint',{
method: 'POST',
body: JSON.stringify({username,password})
})
.then((res)=>{
return res.json();
})
.then((data)=>{
console.log(data)
// you can append new element here
// based on data (success or failure)
})
})

I can't upload PDF file in node.js

I'm trying to create a simple form which can upload file(pdf & image) and texts together using Node.js. Nonetheless, I don't wanna save the pdf file to MySql database, rather I want it to be kept in my internal storage "./uploads" folder. I have used npm formidable, mv, and multer, yet nothing works, anybody knows why?
Here's my html form
<form action="/auth/registerEvent" method = "POST">
<h5> Enter Your Event Information</h5>
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" class="form-control" id="eventName" name="eventName" placeholder="Event Name">
</div>
<div class="form-group">
<label for="eventDescription">Description</label>
<textarea class="form-control" id="eventDescription" name="eventDescription" placeholder="Event Description: No more than 200 words" rows="3"></textarea>
</div>
<div class="form-group">
<label for="eventPoster">Poster</label>
<input type="file" class="form-control" id="eventPoster" name="eventPoster" enctype="multipart/form-data" accept=".jpg, .png, .jpeg">
</div>
<div class="form-group">
<label for="eventProposal">Sponsor Proposal</label>
<input type="file" class="form-control" id="eventProposal" name="eventProposal" enctype="multipart/form-data" accept=".pdf">
</div>
<br>
<button type="submit">Submit</button>
</form>
This is my app.js
const express = require('express');
const path = require('path');
const app = express();
const mysql = require('mysql');
const dotenv = require('dotenv');
dotenv.config({path: './.env'}); // connect to .env
// set views folder
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
// set the directory to css and js
const publicDirectory = path.join(__dirname, './public');
app.use(express.static(publicDirectory));
// Parse URL encoded bodies (as sent by HTML Form)
app.use(express.urlencoded({extended: false}));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
// Define routes
app.use('/', require('./router/pages.js'));
app.use('/auth', require('./router/auth.js'));
// connect to mysql
const db = mysql.createConnection({
host: process.env.LOCALHOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE,
});
db.connect( (err) => {
if (err) console.log(err);
else console.log('Database is connected');
} )
// laptop server
app.listen(3000, (req, res)=>{
console.log('Server is running at localhost:3000');
});
and finally the "auth.js"
const formidable = require('formidable');
const fs = require('fs');
const mysql = require('mysql');
const db = mysql.createConnection({
host: process.env.LOCALHOST,
user: process.env.USER,
password: process.env.PASSWORD,
database: process.env.DATABASE,
});
exports.registerEvent = (req, res) => {
const {
eventName, eventInstitution,
// eventStartDate, eventEndDate,
eventAddress, eventDescription,
eventPoster, eventProposal,
// eoName, eoPhone, eoEmail
} = req.body;
if (req.url === "/registerEvent") {
const form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
const oldPath = eventPoster.path;
const newPath = './uploads' + eventPoster;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err;
});
})
}
// db start
db.query('INSERT INTO registerevent SET ? ', {
EventName: eventName,
Institution: eventInstitution,
// StartDate: eventStartDate,
// EndDate: eventEndDate,
Address: eventAddress,
Description: eventDescription,
// Poster: eventPoster,
// Proposal: eventProposal,
// ContactName: eoName,
// PhoneNumber: eoPhone,
// Email: eoEmail,
}, (error, result) => {
if (error) { console.log(error); }
else {
res.statusCode = 302;
res.setHeader("Location", "/feedback");
res.end();
}
});
// db end
}
So when the customer enters the name & address it goes to sql, and the poster and proposal files will be sent to my "/uploads" directory. Please help

Getting error Cannot POST /public/register-controller on submitting the form

I am creating and login signup system using express js mysql and node js, so as soon as i click on submit button i get an error as :
Cannot POST /public/register-controller
my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>SignUp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="style.css" rel="stylesheet">
<link href="signup.css" rel="stylesheet">
</head>
<body>
<header class="masthead">
<div class="boards-menu"></div>
<div class="logo">
<h1><i class="fab fa-trello logo-icon" aria-hidden="true"></i>Trello</h1>
</div>
</header>
<section class="signup-login">
<form action="/public/register-controller" method="POST">
<div class="username">
<input type="text" placeholder="User Name" name="name"></input>
</div>
<div class="username">
<input type="email" placeholder="Email" name="eamil"></input>
</div>
<div class="username">
<input type="password" placeholder="Password" name="password"></input>
</div>
<div class="button-signup-login">
<button class="add-card-btn btn">Sign Up</button>
<a class="signup-navigator" href="login.html">already a
user?</a>
</div>
</form>
</section>
</body>
</html>
my config.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'trello',
password: 'trello',
database: 'trello'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
my index.js
var express = require("express");
var path = require('path');
var bodyParser = require('body-parser');
var connection = require('./config');
var app = express();
var authenticateController = require('./public/authenticate-controller');
var registerController = require('./public/register-controller');
var dir = path.join(__dirname, 'public');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(dir));
/* route to handle login and registration */
app.post('/api/register', registerController.register);
app.post('/api/authenticate', authenticateController.authenticate);
console.log(authenticateController);
app.post('/public/register-controller', registerController.register);
app.post('/public/authenticate-controller', authenticateController.authenticate);
app.listen(8012);
my register-controller.js
var connection = require('/home/codemymobile/study/trello/config');
var Cryptr = require('cryptr');
var express = require("express");
var cryptr = new Cryptr('myTotalySecretKey');
module.exports.register = function (req, res) {
var encryptedString = cryptr.encrypt(req.body.password);
var sql = 'insert into users(name, email, password) values ?';
var values = [[req.body.name, req.body.email, encryptedString]];
connection.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
res.status(200).send({ error: false, message: "User has been created successfully" });
});
};
my authenticate-controller.js
var Cryptr = require('cryptr');
cryptr = new Cryptr('myTotalySecretKey');
var connection = require('./../config');
module.exports.authenticate = function (req, res) {
var email = req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM users WHERE email = ?', [email], function (error, results, fields) {
if (error) {
res.json({
status: false,
message: 'there are some error with query'
});
} else {
if (results.length > 0) {
decryptedString = cryptr.decrypt(results[0].password);
if (password == decryptedString) {
res.json({
status: true,
message: 'successfully authenticated'
});
} else {
res.json({
status: false,
message: "Email and password does not match"
});
}
}
else {
res.json({
status: false,
message: "Email does not exits"
});
}
}
});
};
so any help that why my file is not getting the path of register-contoller and i am getting this error, please help me out i am quite new to node and express
I think you have made a smaller mistake that is in the html form you are using eamil instead of email in name i.e name="eamil" instead of name="email", either change it here or else change the name you are calling in your js files

Node.JS + mySQL -> How to do the ajax call and access the data on server.js?

So this is my server.js file, where the db is being connected to :
var app = require('express')();
var mysql = require('mysql');
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'user_data',
port: 3306
});
db.connect();
app.get('/', function (req, res) {
res.sendFile(__dirname + "/start.html");
});
app.listen(3000);
So I want to make something like a registration form, where you input your username and password. Then, after you click the submit button, the username and password are supposed to go straight to the mySQL database. So apparently, I need an ajax call which sends the data to that server, but I don't know how to access it on the server.js.
$("button#submit").click(function () {
$.ajax({
'url': 'http://localhost:3000',
'type': 'post',
'data': {
'username': $("#usr").val(),
'password': $("#pwd").val()
},
'success': function (data) {
alert('Data: ' + data);
}
});
})
After I get that data on the server.js, I will obviously want to make a query (to insert the values) but how do I get the data?
This is how I did it for one of my projects:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="/myaction" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="location">Location:</label>
<input type="text" id="location" name="location" placeholder="Enter your location" />
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
Now when user clicks submit /myaction url will hit.
db.connect(function(err,connection){
app.post('/myaction',function(req,res){
console.log(req.body);
var employee={name:req.body.name,location:req.body.location}
db.query('INSERT into employees SET ?',employee,function(err,res){
if(err){
throw err;
}
else{
console.log(res);
}
})
res.send(JSON.stringify(req.body));
})
})
Make sure to include these in your server.js
var express=require('express');
var bodyParser=require('body-parser');
app=express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
So you can see i have defined app.post and I am hitting my url. Then we simply write a sql query to store data.

How to make user registration with Node.js and MongoDB (using mongoose and Express.js)

I need your help. I want to make User registration form and use Nodejs, Express.js, MongoDB(mongoose) and give me very simple example how to make user registration form with: Name, Email, Password and Mobile Number :) I've made mongoose schema and give values like that Name: req.body.name but it won't work :/ In my oppinion I made something bad.
this is my code and if you think it's not correct, please correct it. (sorry for my bad english). this is server.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/addressbookdb');
var express = require('express');
var app = express();
var db = mongoose.connection;
app.use(express.static(__dirname + '/../client'));
app.post("/",function(req,res){
res.end("Registration Succesfully Completed!");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("connected.")
});
// Schema
var RegSchema = mongoose.Schema({
Name: String,
Email: String,
Pass: String,
Num: Number,
reg_time : {
type : Date, default: Date.now
}
}, { collection: 'AddressCol' });
// Model
var UserReg = mongoose.model('UserReg', RegSchema);
// Add in collection
var UserAdd = new UserReg({
Name: req.body.name,
Email: req.body.email,
Pass: req.body.pass,
Num: req.body.num,
});
// Save
UserAdd.save(function (err, fluffy) {
if (err) return console.error(err);
});
});
app.listen(8000, function() {
console.log("Server is running!");
});
and this is my HTML page:
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="name><br>
<input type="email" class="form-control" id="email" placeholder="Email"><br>
<input type="password" class="form-control" id="pass" placeholder="Password"><br>
<input type="number" class="form-control" id="num" placeholder="Number"><br>
<button type="submit" class="btn btn-primary" id="reg-form-btn">Registration!</button>
</div>
<script>
$(document).ready(function() {
$("#reg-form-btn").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var pass = $("#pass").val();
var num = $("#num").val();
$.post("/", {
Name: name,
Email: email,
Pass: pass,
Num: num
});
});
});
</script>
Maybe you should consider Passport or another module.
But you can do something like this:
app.post('/signup', function (req, res, next) {
var user = {
Name: req.body.name,
Email: req.body.email,
Pass: req.body.pass,
Num: req.body.num
};
var UserReg = mongoose.model('UserReg', RegSchema);
UserReg.create(user, function(err, newUser) {
if(err) return next(err);
req.session.user = email;
return res.send('Logged In!');
});
});
app.post('/login', function (req, res, next) {
var email = req.body.email;
var pass = req.body.pass;
User.findOne({Email: email, Pass: pass}, function(err, user) {
if(err) return next(err);
if(!user) return res.send('Not logged in!');
req.session.user = email;
return res.send('Logged In!);
});
});
app.get('/logout', function (req, res) {
req.session.user = null;
});
Then you should have a middleware to handle authentication
function isLoggedIn (req, res, next) {
if (!(req.session && req.session.user)) {
return res.send('Not logged in!');
}
next();
}
And use it on the private routes
app.get("/api", isLoggedIn, function (req, res) {
//Something private
})
Here is a nice tutorial how to make what you want using very useful module passport. Also you will have a quick look at Jade template engine which can be useful in your further learning of creating express apps.
check this tutorial...you can ignore Angular and mongojs if you want:
http://www.phloxblog.in/single-page-application-angular-js-node-js-mongodb-mongojs-module/#.Vc20OXW1Gkq
You are missing body-parser. Try this in your server code:
const bodyParser = require('body-parser');
app.use(bodyParser);
Please refer the question How to access the request body when POSTing using Node.js and Express?

Categories

Resources