NODE JS- EXPRESS:在适用于GET的情况下,无法从HTTP上下文中检索POST和PUT请求的值 [英] NODE JS- EXPRESS: Unable to retrieve value from HTTP Context for POST and PUT requests while it works for GET
问题描述
在Node.js和Express框架中,当它适用于GET时,我无法从HTTP上下文中检索POST和PUT请求的值.我正在使用httpContext设置唯一的requestId标识符,以便在记录日志以跟踪API请求时可以使用它.
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.
我发现HttpContext可以被中间件中的其他一些软件包重置,是否有更好的方法来存储可以在所有模块中访问的请求范围的数据.
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文件
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}`);
});
我从httpContext检索reqId的代码
My code for retrieving the reqId from httpContext
logger.js
logger.js
message = httpContext.get("reqId") ? "RequestId: " +
httpContext.get("reqId")+" "+ message: ""+ message ;
推荐答案
我希望此解决方案可以解决您的问题,并为有此问题的任何人节省很多时间
i hope this solution solve your problem and save many hours for anyone that have this problem
您可以使用bindEmitter来解决问题
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();
});
这篇关于NODE JS- EXPRESS:在适用于GET的情况下,无法从HTTP上下文中检索POST和PUT请求的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!