puzpuzpuz / cls-rtracer

Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
MIT License
311 stars 24 forks source link

Cannot access Request ID in form-data request using runWithId #54

Closed rohitkhatri closed 3 years ago

rohitkhatri commented 3 years ago

I'm trying to access request id in a form-data request with file upload, I'm using runWithId if the request id is passed in headers otherwise expressMiddleware, but It says undefined. Please find the code below:

const express = require('express');
const app = express();
const RequestTracer = require('cls-rtracer');
const multipart = require('connect-multiparty');
const http = require('http');
const server = http.createServer(app);

app.use((req, res, next) => {
    console.log('app.js->reqId:', req.headers['reqid']); // request-100001

    if (req.headers['reqid']) {
        RequestTracer.runWithId(next, req.headers['reqid']);
    } else {
        RequestTracer.expressMiddleware()(req, res, next);
    }
});

// Form Data request with multipart middleware - Doesn't work
app.post('/upload', multipart(), (req, res, next) => {
    res.json({ reqId: RequestTracer.id() }); // undefined
});

// Form Data request without multipart middleware - Works
app.post('/formdata', (req, res, next) => {
    res.json({ reqId: RequestTracer.id() }); // undefined
});

// Works
app.get('/download', (req, res, next) => {
    res.json({ reqId: RequestTracer.id() }); // request-100001
});

const port = 3000;
server.listen(port);
console.log(`Listening on port: ${port}`);

Here's a repl to run it: https://replit.com/@rohitkhatri/cls-rtracer-code#index.js

It says undefined most of the times when id is passed, but works sometimes, but If the request id is not passed, It always works.

Can anyone please help me here?

puzpuzpuz commented 3 years ago

Hi @rohitkhatri

Is there a reason why you do

app.use((req, res, next) => {
    console.log('app.js->reqId:', req.headers['reqid']); // request-100001

    if (req.headers['reqid']) {
        RequestTracer.runWithId(next, req.headers['reqid']);
    } else {
        RequestTracer.expressMiddleware()(req, res, next);
    }
});

instead of

app.use(RequestTracer.expressMiddleware({
  useHeader: true,
  headerName: 'reqid'
}));

?

rohitkhatri commented 3 years ago

Ohh yes, I didn't know about this configuration for the middleware, It's working for me, thanks.