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

Context lost after making the first call to odbc

Open ranjithchev opened this issue 6 years ago • 8 comments

const app = require('express')();
const httpContext = require('express-http-context');
var db = require('odbc')();
const cn = "DRIVER={ODBC Driver 13 for SQL Server};SERVER=SOMESERVER,SOMEPORT;DATABASE=somedb;Trusted_Connection=Yes"

app.use(httpContext.middleware);

app.get('/', (req, res) => {
    httpContext.set('foo', 'bar');

    console.log(httpContext.get('foo'));      // prints 'bar'

    db.open(cn, (err) => {
        if (err) throw err;

        console.log(httpContext.get('foo'));  // prints undefined!
        ...
    });
});
...

My environment is

RedHat Enterprise Linux 7.2 (maipo) Node: 6.9.1 npm: 5.6.0 express-http-context: 1.0.4 (have tried 1.0.0 as well)

ranjithchev avatar Aug 08 '18 17:08 ranjithchev

Thanks for the detailed info! 😃

As I have been looking into these types of issues (context being lost in certain scenarios) I have been looking at the issues in both cls-hooked (on which express-http-context depends) and NodeJS itself. Jeff Lewis, the maintainer of cls-hooked, has some good commentary in https://github.com/Jeff-Lewis/cls-hooked/issues/23 as well as in https://github.com/nodejs/diagnostics/blob/master/tracing/AsyncHooks/problematic-modules.md. (In fact, most of Jeff's contributions are worth reading.)

It looks like many of the consumers of async_hooks and it's dependencies are seeing issues with loss of context and we're doing what we can to try to get it working for everyone. Information like you have provided really helps, so again, thank you!

skonves avatar Aug 08 '18 18:08 skonves

Hi @skonves . Can you help us with an example as requested https://github.com/wankdanker/node-odbc/issues/37#issuecomment-411878915

ranjithchev avatar Aug 10 '18 14:08 ranjithchev

@skonves shouldn’t odbc and mysql be added to that list of modules that break the async hooks?

edevil avatar Sep 05 '18 11:09 edevil

Is there any news/workarounds on making it work with mongoose?

real-artswan avatar Nov 22 '18 11:11 real-artswan

Still having the same issue with mongoose

webdevian avatar Apr 17 '19 13:04 webdevian

same issue when playing with redis as well, context turned undefined after making the call to redis

ayyappayalamati avatar May 07 '19 08:05 ayyappayalamati

Short of implementing these modules with support for CLS, there is no way to ensure request tracking will work once these modules have been called.

rohitsud avatar Jun 12 '19 17:06 rohitsud

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