1

I am currently working on a custom plugin realizing an oauth solution. I decided to implement a proper policy that forwards the incoming login post to an external service. Therefore I have to access the body of the request (property req.body), which is only possible when the required body parser is enabled as express - middleware. Unfortunately, I could not find a comfortable way to enable body parsing within the gateway application. Consequently, I made a workaround by registering a proper route in order to access the underlying expressapp object.

 pluginContext.registerGatewayRoute(app => { app.use(express.json()); }

I do not want to substitute the policy by simply registering a route, because I did not find a way to apply other policies (e.g.: CORS, RATE LIMITER...) to this route.

Please let me know if I oversee something and there is an easier way to enable body parsing.

2 Answers2

1

yes, using "registerGatewayRoute" will apply middleware to every route in EG. What you can do is create a body parser policy. Policy in EG is just a wrapper around ExpressJS middleware so

so body parser policy can contain code like

{
   name: 'bodyparser',
   policy: (actionParams) => express.json()
}

https://www.express-gateway.io/docs/plugins/policy-development/

Now just add this policy as first one in the pipeline and it should provide req.body for all routes going through that pipeline

Serhii Kuts
  • 429
  • 2
  • 9
1

Thanks a lot for your helpful answer. As suggested I created a bodyParser policy. Only a small modification of the previous answer was necessary: Instead of express.json I had to call the function express.json() in order to get required middleware functionality.

const express = require('express');
module.exports = {
   name: 'bodyParser',
   policy: (actionParams) => express.json()
};

Works fine now and body parsing is only enabled where it is really required.