CodeKarl
CodeKarl

Reputation: 135

Fastify get item by title always returning raw JSON as null

I'm just starting with Fastify and ran into an issue where I started creating a get request to get an item by its title, but it keeps giving me a response of null when I try and log the request.body.

My get request:

// Get points by title
fastify.route({
    method: 'GET',
    url: '/pointz/title',
    handler: (request, reply) => {
        return request.body
    }
})

My get request in postman (as code):

curl --location --request GET 'http://localhost:3000/pointz/title' \
--header 'Content-Type: application/json' \
--data-raw '{
    "title": "test"
}'

Screenshot of my input and output in Postman

The expected result would be that the request returns a body that contains the JSON that's being sent, so I can change the code to access request.body.title with a return value of test.

UPDATE: Found a workaround for now. If I change the GET request to a POST request it works just like it's supposed to. I question however if this is considered good practice.

Upvotes: 2

Views: 1792

Answers (1)

Manuel Spigolon
Manuel Spigolon

Reputation: 12900

As discussed in this GitHub Issue GET request validated scheme body? the body should not be send in GET request, a datailed answer about it and fastify ignore it by default.

But legacy code does, and if you need to support it, you have to consume the raw request:

const fastify = require('fastify')({ logger: true })
fastify.get('/', async (req) => {
  let body = ''
  for await (const data of req.raw) {
    body += data.toString()
  }
  return body
})
fastify.listen(3000)

Then your curl command will works as expected.

const got = require('got')
got.get('http://localhost:3000/', {
  json: { hello: 'world' },
  allowGetBody: true
}).then(res => {
  console.log('Returned = ' + res.body)
})

Upvotes: 3

Related Questions