0

I am having an issue in node.js getting the post variable from a post done via a JSON function.
Edit: I can see the form post in Chrome's inspector. The form post is good and well formatted.

The server bit:

app.use(express.bodyParser());
app.post('/user', function (req, res) {
    var tempSession = req.body.tempSession;
    console.log(tempSession);
}

The post from the JSON function:

function postJSONP(url, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", url);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();        
}

The post that call the JSON function:

function LoginSubmit() {
    var action = 'login';
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value; 
    var tempSession = generateSession();

    postJSONP('/user?callback=none&action=' + action + '&user=' + username,{"password":password, tempSession:tempSession});
 }

The form submit from HTML:

 <input id="submit" name="submit" type="submit" value="Login" onclick="LoginSubmit();">

The result from Node.js console:

 undefined
Levi Roberts
  • 1,277
  • 3
  • 22
  • 44

1 Answers1

1

Found a helpful link here on the stack:
Express.js req.body undefined

I realized that req.body was undefined as well. It turns out that you have to configure everything before allowing express to serve any routes.
I had an app.get() before the app.post() section.

The section most helpful was:

You must make sure that you define all configurations BEFORE defining routes.

app.configure(function(){
    app.use(express.bodyParser());
    app.use(app.router);
});
Community
  • 1
  • 1
Levi Roberts
  • 1,277
  • 3
  • 22
  • 44
  • 1
    Yes, this is a common tripping point with express. Please accept your own answer so the question is marked as answered. – Peter Lyons Mar 11 '13 at 16:09