【问题标题】:access variables through request body in node js express通过 node js express 中的请求正文访问变量
【发布时间】:2016-06-15 16:51:31
【问题描述】:

我是节点 js 的新手。我想通过 node js express 访问 HTML 页面中变量的值。

我在脚本标签中编写的 HTML 端代码是

 $.ajax({
                        url: '/modulename',
                        type: 'POST',
                        dataType: 'JSON',
                        data: JSON.stringify([
                        {module:"abc"}]),

                        success: onMemberSucces,
                        error: onMemberError
                    });

我用于我的 js 应用程序的包是

"dependencies": {
"all": "0.0.0",
"body-parser": "^1.15.1",
"cookie-parser": "^1.4.2",
"d3": "^3.5.17",
"express": "^4.13.4",
"jquery": "^2.2.4",
"jsdom": "^9.2.1",
"mssql": "^3.3.0",
"node-sqlserver-unofficial": "1.4.0",
"require": "^2.4.20",
"requirejs": "^2.2.0"
}

我的js应用上的代码是

app.use(express.static('D:/d3 project/project_part1/project_part1/'));
app.use(bodyParser.json());
var server = app.listen(8081);

app.post('/modulename', function (req, res, body) {
modulename = req.body;
console.log("hi \n"+ modulename);
console.log("hi "+ modulename.module);

});

控制台上的输出是

hi [object Object]
hi undefined

我已尝试打印

 modulename.data 

这也会在控制台打印 undefined。我犯了一个非常粗心的愚蠢错误,但我无法弄清楚并且花了好几个小时。请帮助我。提前致谢。

【问题讨论】:

  • 你正在发送一个数组...modulename[0].module.
  • function (req, res) 而不是function (req, res, body)

标签: jquery node.js


【解决方案1】:

把数据改成

data: {module:"abc"},

Jquery 会处理剩下的事情, 在你的节点路由中

console.log(req.body.module)

【讨论】:

    【解决方案2】:

    这里不需要数组,可以改:

    JSON.stringify([
        {
            module: "abc"
        }
    ]),
    

    收件人:

    JSON.stringify({
        module: "abc"
    }),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-13
      • 2019-02-07
      • 2015-07-05
      • 1970-01-01
      • 2012-03-31
      • 2022-01-25
      • 2020-02-17
      • 2018-07-09
      相关资源
      最近更新 更多