Eomm / fastify-raw-body

Request raw body
MIT License
45 stars 10 forks source link

can't get it to work #17

Closed mariusa closed 2 years ago

mariusa commented 2 years ago

Hi,

Trying to get req.rawBody set in fastify route handlers, besides the regular req.body JSON object

import fastifyRawBody from 'fastify-raw-body'

async function plugin(fastify, options) {
...
fastify.register(fastifyRawBody, {
        field: 'rawBody', // change the default request.rawBody property name
        // global: false, // add the rawBody to every request. **Default true**
        encoding: 'utf8', // set it to false to set rawBody as a Buffer **Default utf8**
        runFirst: true, // get the body before any preParsing hook change/uncompress it. **Default false**
        // routes: ['/api/my-route'] // array of routes, **`global`** will be ignored, wildcard routes not supported
    })

...
}

export default plugin

and later

fastify.post('/api/my-route', {

        config: {
            // add the rawBody to this route. if false, rawBody will be disabled when global is true
            rawBody: true
        },
    })
        , (req, reply) => {
console.log('req.rawBody', req.rawBody) //undefined
 return {}
})

I've tried many variations on this, it's always undefined. Found another comment saying it doesn't work too https://github.com/fastify/fastify/issues/707#issuecomment-817224931

What's wrong, please?

Eomm commented 2 years ago

Could you add a Minimal, Reproducible Example?

Looking at the code provided, it should work

mariusa commented 2 years ago

Sure: https://github.com/mariusa/fastify-rawbody-bug

Also tried with global: true

  1. GET http://localhost:5000/api/monitor req.body is null (correct for GET), but req.rawBody is undefined

  2. curl -k -X POST -H "Content-Type: application/json" http://localhost:5000/api/test -d '{"title": "blouse"}'

Eomm commented 2 years ago

Move the raw-body plugin registration before autoload, there should be some conflicts between them

mariusa commented 2 years ago

Thank you, that was it!