Skip to content

Can't access body in preHandler #86

@MihaFriskovec

Description

@MihaFriskovec

When using preHandler in proxy, body is not parsed but instead is overwritten with the request object.

To Reproduce

To reproduce the behavior create a simple reverse proxy and make a POST or PUT request with a body. (JSON)

fastify.register(require("fastify-http-proxy"), {
  upstream: "http://localhost:8080", 
  prefix: "/api/proxy",
  async preHandler(request, reply) {
    console.log(request.body) // This line logs whole fastify request object instead of body
    return
  }
})

Expected behavior

As is preHandler hook on routes, the body should be accessible from proxy's preHandler.

Digging through code I did found a custom body-parser, which I believe disables parsing.

// Code from index.js
fastify.addContentTypeParser('application/json', bodyParser)
fastify.addContentTypeParser('*', bodyParser)

function bodyParser (req, done) {
    done(null, req)
  }

After disabling (commenting out) contentTypeParser the preHandler is working as expected (the body is parsed and accessible).

Is that the expected behavior and if so are there any workarounds?

Your Environment

  • node version: 12.16.1
  • fastify version: 2.12.1
  • os: Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions