【问题标题】:Issue with node.js POST variable from JSON postJSON帖子中的node.js POST变量问题
【发布时间】:2013-03-11 15:52:53
【问题描述】:

我在 node.js 从通过 JSON 函数完成的帖子中获取帖子变量时遇到问题。
编辑:我可以在 Chrome 的检查器中看到表单帖子。表格帖子很好,格式也很好。

服务器位:

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

来自 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();        
}

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

从 HTML 提交的表单:

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

Node.js 控制台的结果:

 undefined

【问题讨论】:

    标签: javascript html json node.js post


    【解决方案1】:

    在堆栈上找到了一个有用的链接:
    Express.js req.body undefined

    我意识到 req.body 也是未定义的。事实证明,您必须先配置所有内容,然后才能允许 express 为任何路线提供服务。
    我在 app.post() 部分之前有一个 app.get() 。

    最有帮助的部分是:

    您必须确保在定义路由之前定义所有配置。

    app.configure(function(){
        app.use(express.bodyParser());
        app.use(app.router);
    });
    

    【讨论】:

    • 是的,这是 express 的常见跳闸点。请接受您自己的答案,以便将问题标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多