elmekiesIsrael
elmekiesIsrael

Reputation: 133

Posting and Redirecting in Node.js Express

Let me start by saying that I'm complete newbie in Node.js. I've read a lot of posts here that are relevant to my problems but they either didn't work for me or I didn't understand the solution. Nodes.js is pretty tricky for me at the moment :/

So here are my questions/problems:

I'm trying to figure out the POST handling and redirecting procedure and I guess I'm missing something because its not working properly.

I'm writing a single page application, so all pages are actually one page divided to sections.

Say I have an HTML form like so (this is in the login section):

 <form method="post" action="/login">
    <input name="email" type="email" id="signin-mail">
    <input name="pass" type="password" id="signin-username">
    <input type="submit" value="send">
 </form>

Here is my Node.js server code:

var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express();

app.use(bodyParser()); 

//
app.get('/login', function(req, res){
    console.log('GET /')
    var html = fs.readFileSync('index.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

//
app.post('/login', function(req, res){
    console.log('POST /');
    console.dir('email: ' + req.body.email +  ' pass: ' + req.body.pass);
    res.status(200).redirect("/index.html#index");
});

app.use(express.static(__dirname + '/'));

port = 8888;
app.listen(port);
console.log('Listening at http://localhost:' + port)

Now, basically, I don't want to do anything except reading the content of the forms, and redirect the user to another page. I see in my terminal that the form data was parsed correctly and it prints the user name and password but instead of redirecting to the #index section of the page, the address changes to localhost/login.

Can someone please shed some light on the whole process of receiving post, extracting the data and redirecting the user?

Thanks!

Upvotes: 1

Views: 5303

Answers (2)

Kundan
Kundan

Reputation: 71

You need to use client side javascript and ajax to achieve this. You may use jquery's post method to submit your forms manually instead of relying on action attribute of <form> Something like this:

$('#myForm').submit(function(event) {
    event.preventDefault(); // Stops browser navigationg

    var dataObject;
    // build a json object, store in information to dataObject

    $.post('/login', dataObject, function(res) {
        consolel.log(res);
        // on success execute this code
    });
});

Update:

Alternatively if you or anyone else here is willing to do file upload as well then you can use this code:

 $("#myForm").submit(function(event){    
 event.preventDefault();

 var formData = new FormData($(this)); 

     $.ajax({
       url: 'login',
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       enctype: 'multipart/form-data',
       processData: false,
       success: function (response) {
           console.log(response);
       }
    });

   return false;
 });

Explanation

On submit event of form, stop default action. Then we create a new formData and pass this of our form. Pass ajax request with parameters such as url, request-method, etc.

Upvotes: 1

dlaxar
dlaxar

Reputation: 549

I just copy&pasted your code and everything worked perfectly.

Basically the way you receive and process POST-data is the way you do it. Express.js (in conjunction with bodyParser) takes a lot of the work away so you can access the data simply.

Also, redirecting works exactly the way you've done it. Just one thing: the process redirecting involves a status code (302). That means that setting the status code to 200 at first is pointless because it's overwritten by the .redirect(url) call.

Hope it helps

Upvotes: 0

Related Questions