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
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.