Response with express and nodejs application - node.js

I have an express server and a login page developed in HTML(with jquery). after login button is hit, jQuery fires a HTTP get request to express server and after user gets verified, user should be redirected to landing page with some data like name, gender, age etc(that is fetched from mongoDB on server itself). When I do res.sendFile or res.redirect, The parameters (name, age, gender) could not be sent on the view which is required there in response.
Jquery:
$("#submit").click(function() {
user = $("#email").val();
pass = $("#password").val();
$.post("https://localhost:443/login", {
user: user,
password: pass
}, function(response) {
if (response) {
alert("login success" + response.userName);
}
});
});
HTML:
<form id="grad">
<h1 style="margin-top: -10px; text-shadow: 1px 1px whitesmoke;">Login</h1>
<h3 style="padding-bottom: 30px;font-size: 22px ">Please enter email ID and password.</h3>
<div class="group">
<input type="email" id="email" name="email"><span class="highlight"></span><span class="bar"></span>
<label>Email ID</label>
</div>
<div class="group">
<input type="password" id="password" name="password"><span class="highlight"></span><span class="bar"></span>
<label>Password</label>
</div>
<div class="group">
<input type="submit" id="submit" class="button buttonRed" value="Login" onclick="validateUser()" />
<input type="reset" class="button buttonRed" value="Reset" />
</div>
</form>
Express:
app.post('/login', function (req, res) {
// some logic to validate user and fetch details, which will be used on view.
res.sendFile('landing**strong text**page.html', { root: "public" } );
})

The post route should save the user in session before returning the response to jQuery code. Essentially the response from post route should be only success or response.
There should also be a get route to redirect the user to home page (or the page where u want the user after login).
This get route will first check if there is a user in session then redirect accordingly.
Use express-session to save the session in app.

Simple solution for starter. This is NOT a practical solution in production site, just for starter who wants to learn the basic.
Jquery
$("#submit").click(function() {
user = $("#email").val();
pass = $("#password").val();
$.post("https://localhost:443/login", {
user: user,
password: pass
}, function(response) {
$('body').append(response); //append html to body returned from /login
});
});
Express Server:
app.post('/login', function (req, res) {
// some logic to validate user and fetch details, which will be used on view.
var userInfo = validateAndFetchDetailFunc();
res.send('Username: ' + userInfo.name + '<br>Gender: ' + userInfo.gender);
})
The real solution should be using session to management the login session for user.
User login with username/password
Create a session at the server side, send back a session key or access token to the client.
When the client request user information, use the session key or access token to retrieve the user info
Render the html page with the user info from the saved session
For express server, you can start to learn session with express-session.

Related

how make checkbox stay checked and reset in node js

I am working on a small project with checkbox and node js. I need the checked box stay on the screen after I click submit button and reset the form after clicking reset button.How can do that?
ejs code
<form method="post" action="/">
<input type="checkbox" name="preference" value="A">A
<input type="checkbox" name="preference" value="B">B
<input type="checkbox" name="preference" value="C">C
<input type="submit" value="Click to Submit">
<input type="reset" value="Erase and Restart">
</form>
node js
express.get('/', (req, res) => {
res.render('form');
});
express.post('/', (req, res) => {
console.log(req.body);
let checkedValue =req.body.preference;
let output = checkedValue==undefined?`You didn' make selection.`:`The preference iterm on menu is ${checkedValue}`;
res.render('form',{
output:output,
});
});
What's going on is that when you submit your form, the webpage is reloaded, so you lose your checked state. You can either save the values on your server and have them pre-checked using an optional checked flag in your ejs template or you can add some client side javascript to handle the form submission for you by writing and event handler for the submit event on the form.
if you expand your ejs template with a conditional checked value on your inputs, your returned page will have them pre-checked
<input type="checkbox" name="preference" <% if (submittedValue === "A") { %>checked<% } %> value="A">A
Or, here's a super simple bit of javascript that would send the values to your server
document.forms[0].addEventListener('submit', function (e) {
e.preventDefault(); // prevent the form from submitting with a page refresh
const data = { values: [] };
e.target.elements.forEach((formEl) => {
if (formEl.checked) data.values.push(formEl.value);
});
fetch('/urlToProcessYourForm', { method: 'POST', body: JSON.stringify(data) });
});

How to handle response in react

I am new to react. Currently I am working on creating a login screen. I have this code:
function login(e) {
fetch('/login')
.then(response => {
if(response === 'fail'){
return(SignIn());
}else{
return(Ide());
}
})
.then((proposals) => {
console.log(proposals);
this.setState({ proposals });
});
}
export default function SignIn() {
const classes = useStyles();
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<Button
type="submit"
fullWidth
onClick={login}
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</form>
</div>
</Container>
);
And then the login handler
app.get('/login', (req, res, next) => {
const { email, password } = req.body;
console.log(email, password);
//User.find({email: })
});
But when I press the submit button, email and password both console log as undefined. How do I send information using react between the client and the server? Thank you in advance
Whenever you use fetch as a way to send info to an endpoint like '/login' above, the req.body needs to be added as part of the fetch call. To do this, people usually do
fetch('/login', {
body: (whatever you send in the form of one object)
});
The body passed in as the second argument can be then used as req.body in your code that console.logs it.
This is not advised though since GET commands usually do not have bodies passed along as the second argument. Usually POST and PUT commands have the body to make it easy to add and change data. What I recommend is do:
fetch('/login/' + email + '/' + password);
This allows for an email and username object to be a part of your url in for your backend to use. This is one of the ways that people do GET commands without passing in a body. With the new format, you should change the backend to be:
app.get('/login/:email/:password', (req, res) => {
const email = req.params.email;
const password = req.params.password;
console.log(email, password);
With :email and :password in the url, this lets you use req.params and then directly call each identifier as the last value.
Btw if you feel like the fetch call above looks messy with the + commands, you can instead do:
fetch(`/login/${email}/${password}`);
Which are Template Literals that make it easier to read code by adding the values directly into the string. (Note they use the ` key next to the 1 key not ' or ")
Also if you want more info on fetch commands, I advise to start with the MDM Documentation. This website is extremely helpful whenever you need to learn something about JS or other web languages.

NodeJS Post request using a Button

I don't know if this is possible or not. All the research I've done has shown that it is possible with a form and text input. But anyways, Using NodeJs & Express I want to be able to click a button on my webpage, and once it's clicked, it sends a post request to my Node.JS server.
Simpler way of saying it:
When button is clicked, send info to the server.
Goal I'm trying to achieve:
When button is clicked, it sends some sort of ID/code/anything to turn on a service from my database. (I have yet to learn how db's work so I am just trying to focus on front end.)
Code I have so far:
app.post("/send", function(req, res){
var newID = req.body.ID;
res.redirect("/action")
});
<form action="/send" method="POST">
<input type="button" name="newID" placeholder="Button">
<button>send</button>
</form>
You do not need to use jQuery or AJAX.
Simply add an input of type submit inside the form tag so that the POST request defined by your form tag is submitted.
Your newID input should be of type text, this allows entering a value in the input field.
The newID value can be retrieved server side with req.body.newID (be sure to use the body-parser middleware).
<form action="/send" method="POST">
<input type="text" name="newID" placeholder="Enter your ID"/>
<input type="submit" value="Click here to submit the form"/>
</form>
For this purposes you should use $.ajax,
example:
$('button').on('click', function() {
$.ajax({
type: 'POST',
url: '/send',
data: { ID: 'someid' },
success: function(resultData) {
alert(resultData);
}
});
});

Specifying routes in sailsjs

i have question about routing in sails.js.
So, i'm following a tutorial about making a login page. it consists of
AuthController.js
module.exports = {
login: function(req , res){
res.view('login'); //view login page
},
authenticate: function(req, res) {
//some auth function
}
};
login.ejs
<div id="login">
<form align="center" action="/login" method="post">
<ul>
<li>
<input type="text" name="username" placeholder="Username"></li>
<li>
<input type="password" name="password" placeholder="Password" ></li>
<li>
<input type="submit" value="Log In"></li>
</ul>
</form>
</div>
and finally this is what makes me confused in routes.js. why this works?
'get /login': {
controller: 'AuthController',
action: 'login'
},
'post /login' : {
controller: 'AuthController',
action: 'authenticate'
},
but this doesn't (i removed the get)?
'/login': {
controller: 'AuthController',
action: 'login'
},
'post /login' : {
controller: 'AuthController',
action: 'authenticate'
},
when i'm using the later route it seems that authentication action is never called when i enter username password, and it's just redirecting me to login page again (it's calling login action instead).
From the sails documentation:
If no verb is specified, the target will be applied to any request that matches
the path, regardless of the HTTP method used (GET, POST, PUT etc.).
URLs are matched against addresses in the list from the top down.
Also the order works from top to bottom. So when you try to POST in /login, it again goes to /login rather than POST /login.
Hope this helps.
As others have said, it's because the routes are compared in order, triggering whichever matches first.
Interestingly that means that if you swap the order, it works as you described:
'post /login' : {
controller: 'AuthController',
action: 'authenticate'
},
'/login': {
controller: 'AuthController',
action: 'login'
},
In sails Js, route.js consists of an address (on the left, e.g. 'get /login') and a target (on the right, e.g. 'AuthController.login'). The address is a URL path and (optionally) a specific HTTP method. When Sails receives an incoming request, it checks the address of all custom routes for matches. If a matching route is found, the request is then passed to its target.
Now, when you remove the get option, & lift your app, & navigate to /login, first the login page is rendered but when the form is posted, it's unable to differentiate b/w the requests as you have omitted get request, so it again calls /login & never reach on the post route.
Reference :http://sailsjs.org/documentation/concepts/routes

Organizing view files in Node.js app

I finished this walkthrough for creating a very basic Reddit clone using the MEAN stack. The app included a few different views, such as a view for all posts, a single post, the login form, and the register form, and all of these views were included in a single file: views/index.ejs.
Is putting all the views together like this common practice, or was it merely for brevity in the tutorial? I was hoping to be able to separate at least the login and register forms from the rest of the views in index.ejs for the sake of organization, but placing them in a login.ejs file in views causes a 404.
Login portion of views/index.ejs
<script type="text/ng-template" id="/login.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-show="error" class="alert alert-danger row">
<span>{{ error.message }}</span>
</div>
<form ng-submit="logIn()"style="margin-top:30px;">
<h3>Log In</h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" ng-model="user.username"></input>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" ng-model="user.password"></input>
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
</script>
Login portion of routes/index.js
router.post('/login', function(req, res, next){
if(!req.body.username || !req.body.password){
return res.status(400).json({message: 'Please fill out all fields'});
}
passport.authenticate('local', function(err, user, info){
if(err){ return next(err); }
if(user){
return res.json({token: user.generateJWT()});
} else {
return res.status(401).json(info);
}
})(req, res, next);
});
Login portion of controller
.state('login', {
url: '/login',
templateUrl: '/login.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth){
if(auth.isLoggedIn()){
$state.go('home');
}
}]
})
I don't understand how the views fit together in this app. What is telling the app to find the login template in index.ejs, and how can I redirect the app to look in a different file?
The way they did this is a little strange, but it was most likely for the sake of brevity.
The reason why it's 404'ing is because of how the routes are set up. There's a single route to serve index.ejs, and the rest of the routing is handled client-side through Angular. In fact, the only reason they used ejs is because they wanted to send it using Express' res.render() method most likely. (Although, since it's just HTML from what I saw, instead of actually using any EJS, they could likely just as easily used Express' res.sendFile() method, or prior to 4.8.0, res.send() in conjunction with Node's builtin fs.readFile to send the plain HTML file.
If you wanted to split out the views you'd have to set up server-side routes, but I guess they were dead set on a single-page app. More commonly, views that are rendered on the server-side are split out into individual files, with a main "layout", in which other views are included into.

Resources