express-http-context icon indicating copy to clipboard operation
express-http-context copied to clipboard

Context undefined when used with routing-controllers

Open davidpablosg opened this issue 7 years ago • 2 comments

I've configured the context on ExpressJs app as a dependency on startup and also set it up as global middleware for every request. The code works like a charm when using routing-controllers for Get, Put and Post But, using @Body decorator into a PUT/POST method, it becomes undefined. Also using body-parser, injecting decorator @json, the context get lost.

Working cases:

@Get('/data') public getData():Promise { httpContext.get('contextId');//Got data return new Promise; }

@Get('/data') public getData(@Req() req):Promise { httpContext.get('contextId');//Got data var a = req.a; return new Promise((resolve) => getData(a){ resolve(response); }); }

@Post('/data') public setData():Promise { httpContext.get('contextId'); //Got data var a = 'some random data'; return new Promise((resolve) => setData(a){ resolve(response); }); }

@Post('/data') public setData(@Req() req):Promise { httpContext.get('contextId'); //Got undefined var a = req.a; return new Promise((resolve) => setData(a){ resolve(response); }); }

Not working cases:

@UseBefore(json()) @Post('/data') public setData(@Req() req):Promise { httpContext.get('contextId'); //Got undefined var a = req.a; return new Promise((resolve) => setData(a){ resolve(response); }); }

@Post('/data') public setData(@Body() data):Promise { httpContext.get('contextId'); //Got undefined return new Promise((resolve) => setData(data){ resolve(response); }); }

@Put('/data') public setData(@Body() data):Promise { httpContext.get('contextId'); //Got undefined return new Promise((resolve) => setData(data){ resolve(response); }); }

davidpablosg avatar Jan 17 '19 16:01 davidpablosg

@davidpablosg It may be a different problem. httpContext middleware must use after body-parser.

reference: https://github.com/skonves/express-http-context/issues/4

jungssunkim avatar Mar 11 '19 06:03 jungssunkim

I have write a tidy npm package http-request-context to do this, using async_hooks, u can try it.

zhujun24 avatar Apr 22 '20 12:04 zhujun24