如何获取数据从jQuery ajax post与ExpressJS

How to get data from jQuery ajax post with ExpressJS

本文关键字:ajax jQuery post ExpressJS 数据 何获取 获取      更新时间:2023-09-26

嗨,我有一个jquery post数据,我要发送:

                 $.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函数中?

在expressjs应用程序中需要一个body解析器中间件来解析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

然后在express应用程序中获取数据只需执行以下命令

console.log(req.body.data)