Search code examples
javascriptnode.jsjson-server

Custom POST with json-server, request.body === undefined


I am using https://github.com/typicode/json-server to mock data for a project.

I have set up the server according to the documentation, but when creating a custom POST request, using curl:

curl 'http://localhost:4200/api/stamoplysninger/beregningsvaerdier/' \
  -H 'Accept: application/json' \
  -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Origin: http://localhost:4200' \
  -H 'Referer: http://localhost:4200/' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: same-origin' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36' \
  -H 'sec-ch-ua: "Chromium";v="103", ".Not/A)Brand";v="99"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "Linux"' \
  --data-raw '{"virkningsaar":2025,"workzonenummer":"12-1234567",
"msbOevrigeEjendommeProcent":81.2,"msbAlmeneBoligerProcent":0,
"afsavnsrentesatsProcent":12.99,"forsigtighedsprincipProcent":100,
"grundskyldMaxVaerdiPromille":669,"grundskyldMinVaerdiPromille":48,
"grundskyldMaxVaerdiProduktionsjordPromille":551.27,
"grundskyldMinVaerdiProduktionsjordPromille":4,
"daekningsafgiftMaxOffentligPromille":373,
"daekningsafgiftMaxErhvervPromille":639}' \
  --compressed

I cannot read the body of the request:

server.post('/api/stamoplysninger/beregningsvaerdier/', (req, res) => {
  console.log(req.body) // logs 'undefined'
})

I have also explicitly set

server.use(jsonServer.bodyParser);

Json-server is otherwise set as per default.


Solution

  • From the code you provided the error is not immediately reproducible. But I was able to create a situation where the problem can occur. But I am not sure if that's the exact issue you are facing.

    It can happen if you apply the body-parser AFTER you define your route.

    E.g. This does not work

    server.post('/test/', (req, res) => {
      console.log(req.body)
      //Undefined
    })
    server.use(jsonServer.bodyParser)
    

    This does:

    server.use(jsonServer.bodyParser)
    server.post('/test/', (req, res) => {
      console.log(req.body)
      //The Json Body
    })