Runny Yolk Runny Yolk - 11 months ago 40
Node.js Question

Receiving Jquery POST data in Express

Edit See the accepted answer below for the fix. I also had to remove the line

contentType: 'appliction/json',
from my POST request.

I'm trying to send a string to Node.js / Express, but
is undefined server-side.

Client jQuery:

traditional: true,
url: '/matches',
contentType: 'appliction/json',
data: viewedProfiles,
dataType: 'json',
success: function(response){


app.use(bodyParser.json());'/matches', isLoggedIn, function(req, res){
console.log(req.body) // this is undefined
var loadedProfiles = []

I've tried:

  • not specifying 'dataType'

  • setting
    data: JSON.stringify(viewProfiles)

  • splitting the string into an array on the client, and then having jQuery stringify it

  • looking for req.params instead of req.body (clutching at straws)

I can see the XHR request in dev tools, and it contains the string I'm expecting.

What super obvious thing am I missing to send the data to Express?


Answer Source

Your server side code looks fine but you need to use $.ajax() rather than $.post() function because $.post() function send data into url (with url encoded). So your jquery code would be

        url: '/matches',
        type: 'POST',
        contentType: 'appliction/json',
        data: JSON.stringify({"viewedProfiles": viewedProfiles}),
        success: function(response){

I hope this will help you