Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NODE JS- EXPRESS: Unable to retrieve value from HTTP Context for POST and PUT requests while it works for GET

In Node.js and Express framework, I am unable to retrieve value from HTTP Context for POST and PUT requests while it works for GET. I am using httpContext to set a unique requestId identifier so that I can use it while logging to trace API requests.

I found out that HttpContext could be reset by some other packages in middle ware, is there a better way to store data for a request scope which could be accessed in all modules.

app.js file



        const app = express();
        app.use(httpContext.middleware);
        //Assign unique identifier to each req
        app.use(function (req, res, next) {
          let test = uuidv1();
          httpContext.set("reqId", test);
          next();
        });

        const PORT = process.env.PORT || 3001;
        Connection.setupPool();
        app.use(express.json());
        app.use(helmet());
        if (app.get("env") === "development") {
          app.use(morgan("tiny"));
        }

        //use to access a resource in the root through url
        app.use(express.static("resource"));

        app.use("/users", userRouter);
        //Code For Instagram authentication Using Passport
        logger.info("End-Instagram Authentication Configuration");
        app.listen(PORT, () => {
          logger.info(`app running port ${PORT}`);
        });

My code for retrieving the reqId from httpContext

logger.js

   message = httpContext.get("reqId") ? "RequestId: " + 
             httpContext.get("reqId")+" "+ message: ""+ message ;
like image 345
regShank Avatar asked Apr 10 '19 11:04

regShank


2 Answers

I am having the same issue. Attempted the bindEmitter solution above and that did not work.

After a few trail and errors REF#1 removing the 'Content-Type': 'application/json' header from my clients POST invocation allowed values in the context to be set/retained.

This led me to suspect there was an issue with how the body-parser(v1.19.0) middleware and express-http-context(v1.2.3) interacts.

When I reversed the order of the middleware such that body-parser comes before express-http-context httpContext was working as expected (without having to do REF#1 ) E.g:

app.use(bodyParser.json()); //must come before
app.use(httpContext.middleware);
like image 154
Shivam Sinha Avatar answered Sep 23 '22 11:09

Shivam Sinha


i hope this solution solve your problem and save many hours for anyone that have this problem

you can just use bindEmitter to solve the problem

app.use((req, res, next) => {
    httpContext.ns.bindEmitter(req);
    httpContext.ns.bindEmitter(res);
    var requestId = req.headers["x-request-id"] || uuidv4();
    httpContext.set("requestId", requestId);
    console.log('request Id set is: ', httpContext.get('requestId'));
    next();
});
like image 36
phpniki Avatar answered Sep 25 '22 11:09

phpniki