gpt4 book ai didi

node.js - Node JS-表达 : Unable to retrieve value from HTTP Context for POST and PUT requests while it works for GET

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:25 25 4
gpt4 key购买 nike

在 Node.js 和 Express 框架中,当它适用于 GET 时,我无法从 POST 和 PUT 请求的 HTTP 上下文中检索值。我正在使用 httpContext 设置唯一的 requestId 标识符,以便我可以在记录跟踪 API 请求时使用它。

我发现 HttpContext 可以被中间件中的一些其他包重置,有没有更好的方法来存储可以在所有模块中访问的请求范围的数据。

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 的代码

记录器.js

   message = httpContext.get("reqId") ? "RequestId: " + 
httpContext.get("reqId")+" "+ message: ""+ message ;

最佳答案

我希望这个解决方案可以解决您的问题并为遇到此问题的任何人节省很多时间

你可以只使用 bindEmitter 来解决问题

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 - Node JS-表达 : Unable to retrieve value from HTTP Context for POST and PUT requests while it works for GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com