I am new to node . Whatever I am trying to is a simple from submission and after submission redirect to specific template . Here is my directory structure
Here is my index.js
file
var app = require('express')();
var http = require('http').Server(app);
var express = require('express')
var bodyParser = require('body-parser')
app.get('/', function(req, res) {
res.sendFile(__dirname + '/login.html');
});
app.post('/login', function(request, response) {
console.log(request.body.user);
console.log(request.body.password);
if (request.body.user === "test@gmail.com" && request.body.password === "123") {
console.log("logged in");
response.statusCode = 200;
response.setHeader("Location", "/home");
response.end();
}
});
app.get('/home', function(req, res) {
res.sendFile(__dirname + '/test.html');
});
http.listen(3001, function() {
console.log('listening on *:3001');
});
In my login.html
file I have a simple form
<label for="user" class="sr-only">Email address</label>
<input type="email" id="user" class="form-control" name="user[email]" placeholder="Email address" required autofocus autocomplete="on">
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="user[password]" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="button" id="submit">Sign in</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var user, pass;
$("#submit").click(function(event) {
user = $("#user").val();
pass = $("#password").val();
$.post("/login", {user: user, password: pass}, function(data) {
if (data === 'done')
{
alert("login success");
}
});
});
});
</script>
When I run my app at localhost:3001
login.html
appears , if I submit the form with username:test@gamil.com
and password:123
it doesn't redirect to test.html
, though I can read the console message "logged in"
.
Instead of making the request to /login
through an AJAX call ($.post()
), just let the form submit to it instead:
<form action='/login' method='post'>
...
</form>
In your current situation, you're redirecting the AJAX request to /home
, not your entire page.
Also, your handler does nothing when the username and/or password don't match, which means that the request will stall. You need to send a response back in that case as well (perhaps redirect to an error page, or to the login page again).