首页 > 解决方案 > 如何在下一个 js 中访问方法内的请求标头?

问题描述

我是使用下一个 js 的新手,有什么方法可以访问方法内的请求标头,而无需将 de 值作为参数传递给方法?我需要在方法中记录一个名为“x-transaction-id”的标头,但我不想重新传递参数。

例如,这是我的控制器

export default nextConnect()
  .use(AuthHandler)
  .use(RequestContextMiddleware) // NEED TO BE BEFORE LOGGER MIDDLEWARE
  .use(LoggerMiddleware)
  .get(async (req: ExtendedApiRequest, res: NextApiResponse<ResumeCountResponse>) => {
    try {
      const { cookies, userId } = req;
      const transactionId = req.headers['x-transaction-id']

      const resumeService = ResumeServiceFactory.make();
      const resumeCount = await resumeService.getResumeListCountOfUser(cookies.cactk, userId);
      res.status(200).json({ data: resumeCount, error: null });
    } catch (error) {
      res.status(500).json({ data: null, error: error.message });
    }
  });

我需要直接在服务方法中记录事务 ID

class ResumeService {
  cache: Cache;

  constructor(cache: Cache) {
    this.cache = cache;
  }

  async getResumeListCountOfUser(token: string, userId: number): Promise<number> {
    try {
      try {
        const dataCache = await this.cache.readCache("any_key");
        if (dataCache) {
          const result = JSON.parse(dataCache);
          return result.data.length;
        }
      } catch (error) {
        const transactionId = ?????
        Logger.error(
          `[Read cache error resumeService]: ${error.message}`,
          transactionId,
          error,
        );
      }
   }
}

标签: node.jsexpressnext.js

解决方案


推荐阅读