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.