【问题标题】:How to get data from jQuery ajax post with ExpressJS如何使用 ExpressJS 从 jQuery ajax 帖子中获取数据
【发布时间】:2015-06-02 04:23:50
【问题描述】:

您好,我有一个要发送的 jquery 发布数据:

                 $.ajax({
                    type: "POST",
                    url: app.config.backend_2 + '/notifications/usernames',
                    data: data,
                    contentType: 'application/javascript',
                    dataType: 'json',
                    success: function (result) {
                        console.log(result);
                    }
                });

这是我的快递收货人:

 exports.save_usernames_for_notifications = function (req, res, next) {
    var start = function () {
       console.log(req);
    };

     start();

};

如何从 ajax 获取数据以将其记录到 save_username_for_notifications 函数中?

【问题讨论】:

  • 除非您想使用 JSONP,否则将您的内容类型更改为 application/json?

标签: javascript jquery ajax node.js express


【解决方案1】:

您需要在您的 expressjs 应用程序中使用一个正文解析器中间件来解析您的 JSON req 对象

https://www.npmjs.com/package/body-parser

要配置它,你需要这个代码

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // this is used for parsing the JSON object from POST

然后要在您的快速应用程序中获取您的数据,只需执行此操作

console.log(req.body.data)

【讨论】:

  • 是的,这行得通。在需要正文解析器后将其放在最上面。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 2021-12-05
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多