简体   繁体   English

JSON帖子中的node.js POST变量问题

[英]Issue with node.js POST variable from JSON post

I am having an issue in node.js getting the post variable from a post done via a JSON function. 我在node.js中遇到问题,无法通过JSON函数从发布中获取发布变量。
Edit: I can see the form post in Chrome's inspector. 编辑:我可以在Chrome的检查器中看到表单发布。 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: JSON函数的帖子:

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: 调用JSON函数的帖子:

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: 从HTML提交表单:

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

The result from Node.js console: 来自Node.js控制台的结果:

 undefined

Found a helpful link here on the stack: 在堆栈上找到了一个有用的链接:
Express.js req.body undefined Express.js req.body未定义

I realized that req.body was undefined as well. 我意识到req.body也未定义。 It turns out that you have to configure everything before allowing express to serve any routes. 事实证明,在允许express服务任何路由之前,您必须配置所有内容。
I had an app.get() before the app.post() section. 我在app.post()部分之前有一个app.get()。

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM