i've got a problem which i can't resolve for some time now, i tried to research but nothing comes to my mind.
First of all - This is my app:
server.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const MongoClient = require('mongodb').MongoClient
app.use(bodyParser.urlencoded({ extended: true }))
app.use("/node_modules", express.static('node_modules'));
app.use(express.static(__dirname + '/static'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
app.post('/quotes', (req, res) => {
db.collection('quotes').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log(req.body)
console.log('saved to database')
res.redirect('/')
})
})
var db
MongoClient.connect('mongodb://127.0.0.1/db', (err, database) => {
if (err) return console.log(err)
db = database
app.listen(3000, () => {
console.log('listening on 3000')
})
})
index.html
<!DOCTYPE html>
<html ng-app='app'>
<head>
<link rel="stylesheet" href="/assets/css/my.css" />
</head>
<body>
<div ng-controller='PostsCtrl' class='container'>
<h1>
<center>Shoutbox</center>
</h1>
Your Nick
<form role='form'>
<div class='form-group'>
<div class="input-group">
<input ng-model="postName" class='form-control'>
</div>
</div>
</form>
Your Shout
<form role='form'>
<div class='form-group'>
<div class="input-group">
<input ng-model="postBody" class='form-control'>
<span class='input-group-btn'>
<button ng-click='addPost()' class='btn btn-default'>Add Shout</button>
</span>
</div>
</div>
</form>
<ul class='list-group'>
<li ng-repeat='post in posts' class='list-group-item'>
<strong>#{{ post.username }}</strong>
<span>{{ post.body }}</span>
</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('app', [])
app.controller('PostsCtrl', function($scope, $http) {
$scope.addPost = function() {
$http({
method: 'POST',
url: '/quotes',
data: {
"Object": "Value"
}
}).then(function(success) {
console.log("sent")
}, function(error) {
cosnole.log(err)
});
if ($scope.postBody) {
$scope.posts.unshift({
username: $scope.postName,
body: $scope.postBody
}),
$scope.postBody = ''
$scope.postName = ''
}
}
$scope.posts = []
})
</script>
</body>
</html
Now here's my problem:
Everything seems to be ok, data is sent but when i'm browsing mongo for entries - only ID is saved, no data whatsoever.
I have no idea where it's going wrong.
This is what's saved to database:
{ _id: 59304d915d20041a272bd96d }
When i manually save json to database - it works ok so i assume thats not problem with mongo itself.
Thanks for every hint you provide.
/edit
Apparently i have resolved the issue by using app.use( bodyParser.json() ); on the server side.
To be closed.
Related
I'm building a NodeJS Express & MongoDB Web application.
However, since I'm trying to use some AJAX feature to load and display comments on the post page, I'm getting an issue and the "post-detail" page is not displaying.
My code seems fine though. So, I'm not able to find where is the mistake.
When I check this error message:
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
Is there someone who can check my code and let me know what's wrong with it?
I think there is a problem in the route or the paths?
app.js:
const path = require('path');
const express = require('express');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use('/', adminRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
res.status(500).render('500');
});
db.connectToDatabase().then(function () {
app.listen(3000);
});
routes\home\posts.js:
const express = require('express');
const mongodb = require('mongodb');
// const uuid = require('uuid');
const db = require('../../data/database');
const ObjectId = mongodb.ObjectId;
const router = express.Router();
router.get('/blog', async function (req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, 'author.name': 1, imagePath: 1 })
.toArray();
res.render('posts', { posts: posts });
});
router.get('/blog/:id', async function (req, res, next) {
let postId = req.params.id;
try {
postId = new ObjectId(postId);
} catch (error) {
return res.status(404).render('404');
// return next(error);
}
const post = await db
.getDb()
.collection('posts')
.findOne({ _id: postId }, { summary: 0 });
if (!post) {
return res.status(404).render('404');
}
post.humanReadableDate = post.date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
post.date = post.date.toISOString();
res.render('post-detail', { post: post });
});
router.get('/blog/:id/comments', async function (req, res) {
const postId = new ObjectId(req.params.id);
const comments = await db
.getDb()
.collection('comments')
.find({ postId: postId })
.toArray();
res.json(comments);
});
router.post('/blog/:id/comments', async function (req, res) {
const postId = new ObjectId(req.params.id);
const newComment = {
postId: postId,
title: req.body.title,
text: req.body.text
};
await db.getDb().collection('comments').insertOne(newComment);
res.redirect('/blog/' + req.params.id);
});
module.exports = router;
views\home\post-detail.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('../admin/includes/head', { title: 'Post title' }) %>
<link rel="stylesheet" href="/admin/styles/posts.css" />
<link rel="stylesheet" href="/admin/styles/forms.css" />
<script src="/home/scripts/comments.js" defer></script>
</head>
<body>
<%- include('../admin/includes/header') %>
<main id="post-detail">
<article class="post-item">
<img src="/<%= post.imagePath %>" alt="<%= post.title %>" />
<h1><%= post.title %></h1>
<section id="post-meta">
<address>
<a href="mailto:<%= post.author.email %>"
><%= post.author.name %></a
>
</address>
|
<time datetime="<%= post.date %>"><%= post.humanReadableDate %></time>
</section>
<hr />
<section>
<p id="body"><%= post.body %></p>
</section>
</article>
<section id="comments">
<% if (!comments) { %>
<p>
This post might have comments. You can load them if you want to view
them.
</p>
<button
id="load-comments-btn"
class="btn btn-alt"
data-postid="<%= post._id %>"
>
Load Comments
</button>
<% } else if (comments.length === 0) { %>
<p>No comments found.</p>
<% } else { %>
<ol>
<% for (const comment of comments) { %>
<li><%- include('includes/comment-item', { comment: comment }) %></li>
<% } %>
</ol>
<% } %>
</section>
<section id="comments-form">
<h2>Leave a comment</h2>
<form action="/posts/<%= post._id %>/comments" method="POST">
<div class="form-control">
<label for="title">Comment title</label>
<input type="text" id="title" name="title" required />
</div>
<div class="form-control">
<label for="text">Your comment</label>
<textarea name="text" id="text" rows="3" required></textarea>
</div>
<button class="btn">Save Comment</button>
</form>
</section>
</main>
</body>
</html>
views\home\includes\comments\comment-item.ejs:
<article class="comment-item">
<h2><%= comment.title %></h2>
<p><%= comment.text %></p>
</article>
public\home\scripts\comments.js:
const loadCommentsBtnElement = document.getElementById('load-comments-btn');
async function fetchCommentsForPost() {
const postId = loadCommentsBtnElement.dataset.postid;
const response = await fetch(`/blog/${postId}/comments`);
const responseData = await response.json();
console.log(responseData);
}
loadCommentsBtnElement.addEventListener('click', fetchCommentsForPost);
I have noticed that when I remove the code logic for displaying comments on "post-detail.ejs", the page displays and the form for adding comments as well.
Edit: I added console.error(error) before res.status(500).render('500') and I get the following error message:
ReferenceError:
C:\Users\DELL\Desktop\node-com4muz-filedata-database\views\home\post-detail.ejs:30
28|
29|
30| <% if (!comments) { %>
31|
32| This post might have comments. You can load them if you want to view
33| them.
comments is not defined
at eval ("C:\Users\DELL\Desktop\node-com4muz-filedata-database\views\home\post-detail.ejs":40:8)
at post-detail (C:\Users\DELL\Desktop\node-com4muz-filedata-database\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\Users\DELL\Desktop\node-com4muz-filedata-database\node_modules\ejs\lib\ejs.js:274:36)
at View.exports.renderFile [as engine] (C:\Users\DELL\Desktop\node-com4muz-filedata-database\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\Users\DELL\Desktop\node-com4muz-filedata-database\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\DELL\Desktop\node-com4muz-filedata-database\node_modules\express\lib\application.js:657:10)
at Function.render (C:\Users\DELL\Desktop\node-com4muz-filedata-database\node_modules\express\lib\application.js:609:3)
at ServerResponse.render (C:\Users\DELL\Desktop\node-com4muz-filedata-database\node_modules\express\lib\response.js:1039:7)
at C:\Users\DELL\Desktop\node-com4muz-filedata-database\routes\home\posts.js:49:7
at processTicksAndRejections (node:internal/process/task_queues:96:5) { path:
'C:\Users\DELL\Desktop\node-com4muz-filedata-database\views\home\post-detail.ejs'
}
I fixed the issue.
On views\home\post-detail.ejs on line 49, I replaced:
res.render('post-detail', { post: post });
by:
res.render('post-detail', { post: post, comments: null });
This question already has an answer here:
ExpressJS request body is empty if i don't use multer
(1 answer)
Closed 7 months ago.
I have a form with two numeric input fields that I'd like to send to the backend, but req.body is always empty. Here is my form:
<form
class="mt-3"
id="myForm"
enctype="multipart/form-data"
action="/submit-thing1and2"
>
<div class="mb-2">
<label for="thing1" class="form-label"
>Thing 1</label
>
<input
type="number"
class="form-control"
id="thing1"
name="thing1"
required
/>
</div>
<div class="mb-2">
<label for="thing2" class="form-label"
>Thing 2</label
>
<input
type="number"
class="form-control"
id="thing2"
name="thing2"
required
/>
</div>
<div class="form-group-row mb-3">
<button id="submitThings" type="submit" class="btn btn-primary">
Submit Things
</button>
</div>
</form>
I have tried using enctype="application/json", "text/html", and "application/x-www-form-urlencoded", and all of them still return an empty object in req.body.
Here is my post request:
form = document.getElementById("myForm");
form.addEventListener("submit", async (event, arg) => {
event.preventDefault();
console.log(event.target.action);
console.log(event.target);
let data = new FormData(event.target);
console.log(data.toString());
fetch(event.target.action, {
method: "post",
body: new FormData(event.target),
})
.then((res) => {
console.log(res.status);
return res.text();
})
.then((data) => {
console.log(data);
});
});
And here is my server-side handling of the post request - the console.log works, just shows an empty object:
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 5000;
const app = express();
app.use(express.static(path.join(__dirname)));
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.post("/submit-thing1and2", async (req, res) => {
console.log("req.body", req.body);
res.send(req.body);
});
app.get("/", (req, res) => {
res.sendFile("./html/index.html", { root: __dirname });
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
Use multer to parse multipart/form-data requests:
app.post("/submit-thing1and2",
multer().fields([{name: "thing1"}, {name: "thing2"}]),
async function(req, res) {
...
});
Please educate me about how am I going to connect the CSS to the server. I've followed two tutorials on youtube, one is using node.js and nodemailer. With this, I use a localhost to run my website but the CSS and js I made from the second tutorial (pop-up when button is clicked) won't work on the localhost but when I clicked the html file itself.
Is this because the tutorials are for different kinds of website? like static and dynamic?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Document</title>
</head>
<body>
<h1>Welcome to my App</h1>
<form>
<div>
<label for="email">Sender's Email: </label>
<input type="email" id="email" placeholder="Your Email"> <br>
</div>
<div>
<label for="classNum">To whom: R</label>
<input type="number" id="classNum" placeholder="class#" min="1" max="31"> <br>
</div>
<div>
<label for="subject">Subject: </label>
<input type="text" id="subject" placeholder="Subject"> <br>
</div>
<div>
<label for="text">Letter: </label> <br>
<textarea name="text" id="text" cols="30" rows="10"></textarea> <br>
</div>
<input type="submit" value="Submit" class="modal-button" data-modal-target="#modal">
<div class="modal" id="modal">
<div class="modal-header">
<div class="title">Letter Sent!</div>
</div>
<div class="modal-body">
Pressing this button will refresh the page.
<div><button data-close-button class="refresh-button">Send another letter</button></div>
</div>
</div>
<div id="overlay"></div>
</form>
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('form').on('submit', (e) => {
e.preventDefault();
const email = $('#email').val().trim();
const subject = $('#subject').val().trim();
const text = $('#text').val().trim();
const classNum = $('#classNum').val().trim();
const data = {
email,
subject,
text,
classNum
};
$.post('/email', data, function(){
console.log('Server received our data')
});
});;
</script>
</body>
</html>
This is the server.js
const express = require('express');
const sendMail = require('./mail')
const log = console.log;
const app = express();
const path = require('path');
const PORT = 8080;
app.use(express.urlencoded({
extended: false
}));
app.use(express.json());
app.post('/email', (req, res) => {
const { subject, email, text, classNum} = req.body;
console.log('Data: ', req.body);
sendMail(email, subject, text, classNum, function(err, data){
if (err){
res.status(500).json({ message: 'Internal Error'});
}
else{
res.json({ message: 'Email sent!' });
}
});
// res.json({ message: 'Message received!' })
});
app.get('/', (req, res) =>{
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
app.listen(PORT, () => log('Server is starting on PORT: ', 8080));
And this one is for the pop-up, script.js
const openModalButtons = document.querySelectorAll('[data-modal-target]');
const closeModalButtons = document.querySelectorAll('[data-close-button]');
const overlay = document.getElementById('overlay');
var path = require('path') //from stackoverflow
app.use(express.static(path.join(__dirname, 'public')));
openModalButtons.forEach(button => {
button.addEventListener('click', () => {
const modal = document.querySelector(button.dataset.modalTarget)
openModal(modal)
})
})
closeModalButtons.forEach(button => {
button.addEventListener('click', () => {
const modal = button.closest('.modal')
closeModal(modal)
})
})
function openModal(modal) {
if (modal == null) return
modal.classList.add('active')
overlay.classList.add('active')
}
function closeModal(modal) {
if (modal == null) return
window.open("https://www.w3schools.com");
}
Please tell me if I need to include the CSS and the mail.js .
If you want to allow users or browsers to get files from your server, you need to add them to your server-side code. For example, you've added a stylesheet reference to your index.html, so the browser will try to get that file (/style.css) from the server. You haven't put any reference to this on the server side, so the server will respond with 404 Not Found or another error.
In order to make the server respond to a request for "/style.css", you need to add the following to your server-side index.js:
app.get("/style.css" /*name of file in index.html*/, (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'style.css')); //CHANGE THIS TO THE NAME OF THE FILE ON THE SERVER
});
The same needs to happen for your browser script, script.js:
app.get("/script.js" /*name of file in index.html*/, (req, res) => {
res.sendFile(path.join(__dirname, 'views', 'script.js'));
});
app.get tells express to respond to a GET request to the first parameter: in the example, that's "/style.css". If you wanted to respond to a GET request to "/foobar", then you would write app.get("/foobar", (req, res) => {/*SOME CODE HERE*/}); . The reason why it wasn't working was becuase when the browser tried to find style.css and script.js, the server didn't know what to do because you hadn't included app.get for those files, and therefore responded with an error.
This might be confusing due to the architecture of how this works. Look at this diagram:
==== HOW A WEBSITE SENDS A FILE ====
______ ____ ______
/ . . \ GET /file [____] READ / |
| j | ======> [____] ======> | file |
\__===_/ <====== [____] <====== | |
user RESPONSE server |_______|
I am writing a Node.js script and having problems with integration of a "login" form. I can do it using a static HTML page, however using a dynamic ".ejs" page is causing problems...my form fields are reported as "undefined".
var helmet = require('helmet');
var bodyParser = require('body-parser')
//var cookieParser = require('cookie-parser');
//var csurf = require('csurf');
//Use Express module
var express = require('express');
var app = express();
var io = require("socket.io"); //web socket external module
var easyrtc = require("easyrtc"); //EasyRTC external module
app.use(helmet());
//Statically serve files in these directories
app.use("/js", express.static(__dirname + '/easyrtc/js'));
app.use("/images", express.static(__dirname + '/easyrtc/images'));
app.use("/css", express.static(__dirname + '/easyrtc/css'));
//For my homepage
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs') //set the view engine to ejs
app.use("/css", express.static(__dirname + '/public/css'));
app.use("/img", express.static(__dirname + '/public/img'));
//Needed to parse form data
app.use(bodyParser());
//var csrfProtection = csurf({ cookie: true });
//parse cookies...we need this because "cookie" is true in csrfProtection
//app.use(cookieParser());
//global variables
var loggedIn = false,
password = 'password';
var title = 'This is a heading';
var message = 'Steve is NOT available';
var presenter = 'Username'
var passport = 'Password'
//Temporary home page
app.get('/', function (req, res) {
var site = req.hostname; //example returns "localhost"
var splits = site.split("."); //"split" on "periods"
console.log("site is: " + site);
console.log("first split is: " + splits[0]);
console.log("second split is: " + splits[1]);
if (loggedIn == true) {
res.render('index', {title: 'available', message: 'Steve is available...'});
console.log("homepage -logged in");
}
else {
console.log("homepage -not logged in");
res.render('login', {
usr: {},
pword: {},
data: {},
errors: {}//,
// csrfToken: req.csrfToken()
});
}
});
//Respond to POST from login form
app.post('/login', function (req, res) {
console.log('post to /login');
var usr_STR = String(req.body.usr)
var pass_STR = String(req.body.pword)
console.log("req.body.usr: " + req.body.usr + " req.body.pword: " + req.body.pword);
console.log("usr_STR: " + usr_STR + " pass_STR: " + pass_STR);
if (loggedIn == true) {
res.send("Already logged in.");
}
else {
console.log("Posted data:" + JSON.stringify(req.body));
console.log("req.body.pw:" + req.body.pw);
console.log("req.body.pword:" + req.body.pword);
console.log("req.body.usr:" + req.body.usr);
if (req.body.pword == password) {
loggedIn = true;
res.send("You are logged in.");
console.log("Logged in");
// Start EasyRTC server
var easyrtcServer = easyrtc.listen(app, socketServer);
}
else {
res.render('login', {
data: req.body, //{ presenter, passport }
errors: {
presenter: {
msg: 'Your username does not look right'
},
passport: {
msg: 'Your password does not look right'
}
}//,
// csrfToken: req.csrfToken()
});
}
}
});
//Error Handling
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!")
});
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
});
// Start server on port 8080
var webServer = app.listen(8080);
console.log('Listening on port ' + 80);
// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer);
I am seeing my console report back the following to me:
Posted data:{}
req.body.pword:undefined
req.body.usr:undefined
I am still somewhat new to working with Node.Js and obviously I'm having some confusion about how to pass the parameters from my (.ejs) form to my route handler within the req.body ...any advice would be GREATLY appreciated, I'm really struggling trying to figure this out. Thank you in advance. Regards.
NOTE: As can be seen in my code, I removed the references to "csurf" and "cookieparser" since in my earlier runs this information WAS returned within the "req.body"...so I thought they were somehow interfering...however it seems there is something else going on.
Here is the associated HTML for the login form:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="form-header">
<% if (Object.keys(errors).length === 0) { %>
<h2>Login Form</h2>
<% } else { %>
<h2 class="errors-heading">Oops, please correct the following:</h2>
<ul class="errors-list">
<% Object.values(errors).forEach(error => { %>
<li><%= error.msg %></li>
<% }) %>
</ul>
<% } %>
</div>
<form method="post" action="/login" novalidate>
<div class="imgcontainer">
<img src="img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label for="usr"><b>Username</b></label>
<input type="text" placeholder=<%= data.presenter %> name="usr" required>
<% if (errors.presenter) { %>
<div class="error"><%= errors.presenter.msg %></div>
<% } %>
<label for="pword"><b>Password</b></label>
<input type="password" placeholder=<%= data.passport %> name="pword" required>
<% if (errors.passport) { %>
<div class="error"><%= errors.passport.msg %></div>
<% } %>
<button type="submit">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</body>
</html>
You need to use body-parser, just importing it won't work out.
Also checkout body-parser docs
// configure the app to use bodyParser()
// parse urlencoded data type as JSON
app.use(bodyParser.urlencoded({
extended: true
}));
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));
I have an application where I am able to login using my registered users. I want to redirect the logged in users to different home pages based on their roles (enititytypes here). Here is the login controller for the app and also the node.js code along with the login html. I hope somebody can help me.
login.html -
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login User</title>
</head>
<body>
<div ng-controller="loginCtrl">
<h1>Login</h1>
<div class="row">
<div class="col-md-8">
<section>
<form role = "form" data-ng-submit = "SendLoginData()"
class="loginpage">
<h4>Use a local account to log in</h4>
{{ PostDataResponse }}
<br />
<div class="form-horizontal">
<div class="form-group">
<label class="col-md-2 control-label">Email</label>
<div class="col-md-10">
<input type="email" ng-model="email"/>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Password</label>
<div class="col-md-10">
<input type="password" ng-model="password" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Remember me?</label>
<div class="col-md-10">
<input type="checkbox" ng-model="checkboxModel.value1"
ng-true-value="'YES'" ng-false-value="'NO'">
<!-- </form> -->
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Log in</button>
</div>
</div>
<div>
<p>
Register as a new user?
</p>
<p>
Forgot your password?
</p>
</div>
</form>
</section>
</div>
<div class="col-md-4">
<section>
<h4>Use another service to log in.</h4>
<p>
Test content here!
</p>
</form>
</section>
</div>
</div>
</div>
</body>
</html>
app.js -
app.controller('loginCtrl', function($scope, $location, $http) {
console.log("My Controller reporting for duty.");
$scope.SendLoginData = function() {
var data = ({
'LoginEmail' : $scope.email,
'LoginPassword' : $scope.password
});
console.log(data);
console.log(JSON.stringify(data));
JSON.stringify(data);
$http.post('/login', data)
.success(function (data, status, headers, config) {
console.log(status);
if (status == 201) {
$location.path('/');
}
})
.error(function(data, status, header, config){
$scope.PostDataResponse = "Error " +status + ": Email/Password are not matching. Please check your credentials.";
});
};
});
index.js -
var PORT = 4569;
var body_parser = require('body-parser');
var express = require('express')
var app = express();
var bigInt = require('big-integer');
var async = require('async');
var bcrypt = require('bcryptjs');
var location = require('location');
var path = require('path');
var http = require('http');
var sql = require('mssql');
app.use(body_parser.urlencoded({extended: true}));
app.use(express.static('public'));
app.use(body_parser.json());
app.set('views', 'app/views');
app.set('view engine', 'ejs');
var config = {
server: 'localhost',
database: 'chico',
user: 'Soumya',
password: 'secret',
port: 1433
};
app.post('/login', function(req, res) {
console.log(req.body.LoginEmail);
console.log(req.body.LoginPassword);
var dbConn = new sql.ConnectionPool(config);
dbConn.connect().then(function () {
console.log("I am the error 4");
var transaction = new sql.Transaction(dbConn);
console.log("I am the error 5");
transaction.begin().then(function () {
var request = new sql.Request(transaction);
console.log("I am the error 6");
request.query("select Email,EntityType from dbo.Userregister1 where Email = '"+req.body.LoginEmail+"' and PasswordHash = '"+req.body.LoginPassword+"'", function (err, row) {
if(err) {
console.log('Error1');
}
else if (row.rowsAffected[0] == 1) {
console.log('Error2');
res.sendStatus(201);
} else if (row.rowsAffected[0] != 1) {
console.log('Error3');
res.sendStatus(399)
};
})
})
});
});
app.listen(PORT, function () {
console.log('Server Started. You can access the editor from http://localhost:' + PORT)
})
On the server, if you have a way to detect what kind of user logged in (in your code after the error detection block), you would do something like this:
if(row.data['userType'] === "admin") {
res.redirect("/adminPanel");
}
else if(row.data['userType'] === "editor") {
res.redirect("/editorPanel");
}
You would do it similarly for any role you might have on your app. I am not 100% sure on the syntax regarding row.data, since I don't work with MSSQL, but it seems it should be something close to that.