1

Client:

$('#send-button').on('click', () => {
  $.post('/send-data', JSON.stringify({ a: 10, b: 20 }), (data, status) => {
    console.log(data)
  })
})

Server:

const express = require('express')
const app = express()
app.use(express.json())

app.use(express.static(__dirname))

app.post('/send-data', (req, res) => {
  console.log(req.body)
  res.send(JSON.stringify(req.body))
})

app.listen(3000, () => {
  console.log(`Listening on port 3000...`)
})

Expected result:

On button click, both client and server print { a: 10, b: 20 } to the console.

Actual result:

On button click, both client and server print {} to the console.


Why am I getting this result?

EDIT: I am not using body-parser. app.use(bodyParser.json()) is no longer needed as of Express 4.16. The proposed duplicate question asks about express pre-4.16 using body-parser, and the answers do not work for my use-case.

Michael Dorst
  • 6,449
  • 10
  • 35
  • 64

1 Answers1

0

import body-parser and add to your middleware like:

const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.post('/send-data', (req, res) => {
  console.log(req.body)
  res.send(JSON.stringify(req.body))
})

Haven't used jQuery for a bit, but pretty sure you don't think you need to stringify when posting:

$.post( "/send-data", { a: 10, b: 20 })
  .done(function( data ) {
    console.log(data)
  });
Samuel Goldenbaum
  • 15,346
  • 13
  • 51
  • 87