rnldpbln
rnldpbln

Reputation: 674

How to get data from jQuery ajax post with ExpressJS

Hi so I have a jquery post data that i'm sending:

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

and this is my express receiver:

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

     start();

};

What do I do to get the data from the ajax to log it in the save_username_for_notifications function?

Upvotes: 1

Views: 3677

Answers (1)

Tim
Tim

Reputation: 3803

You need a body parser middleware in your expressjs application to parse your JSON req object

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

To configure it, you need this code

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

Then to get your data in your express application just do this

console.log(req.body.data)

Upvotes: 1

Related Questions