无法使用应用程序路由器在下一个js 14的lib文件夹中获取我的环境变量

问题描述 投票:0回答:1

我正在使用 next js 14 应用程序路由器,而不是使用 src 目录...我面临的问题是我的 .env 文件位于根目录中,我想访问 lib 文件夹中的环境变量,该 lib 文件夹是同样在根目录和 lib 文件夹中,我有文件 azure-blob.ts 这是文件中的代码

"use server";

import { BlobServiceClient } from "@azure/storage-blob";

async function uploadToAzureBlobStorage(file: any) {
  console.log("Function is invoking");
  try {
    const azure_string =
      process.env.CONNECTION_STRING;
    console.log("Azure Storage connection string:", azure_string);

    if (!azure_string) {
      throw new Error("Azure Storage connection string is not set");
    }

    const containerName = process.env.CONTAINER_NAME;
    console.log("Container name:", containerName);
    if (!containerName) {
      throw new Error("Azure Blob container name is not set");
    }

    const blobServiceClient =
      BlobServiceClient.fromConnectionString(azure_string);
    const containerClient = blobServiceClient.getContainerClient(containerName);

    const file_key =
      "uploads/" + Date.now().toString() + file.name.replace(/ /g, "-");
    console.log("File key for upload:", file_key);

    const blockBlobClient = containerClient.getBlockBlobClient(file_key);
    await blockBlobClient.uploadBrowserData(file);
    console.log("Upload successful:", file_key);

    return {
      file_key,
      file_name: file.name,
    };
  } catch (error:any) {
    console.error("Error object:", error);
    console.error("Error uploading to Azure Blob Storage:", error.message || "Unknown error");
    throw error;
}
}

export default uploadToAzureBlobStorage;

我尝试在此文件中添加 dotenv 并为其设置多个路径,但每当此函数调用时都不起作用,错误是连接字符串未定义

azure next.js environment-variables
1个回答
0
投票

有几种方法可以给这只猫剥皮。

blob-config.ts

import dotenv from 'dotenv';

dotenv.config({ path: '../yourenvfile.env' });

export const azureConfig = {
  CONNECTION_STRING: process.env.CONNECTION_STRING || '',
  CONTAINER_NAME: process.env.CONTAINER_NAME || '',
};

azure-blob.ts

import { azureConfig } from 'blob-config';

async function uploadToAzureBlobStorage(file: any) {
  const azure_string = azureConfig.CONNECTION_STRING;
  const containerName = azureConfig.CONTAINER_NAME;
  // Rest of the function...
}
© www.soinside.com 2019 - 2024. All rights reserved.