繁体   English   中英

使用 dotenv 加载环境变量仍然返回 undefined

[英]Loading environment variables with dotenv still returns undefined

我在这里不知所措。 按照说明,我的.env文件位于我的根目录中。 我已经通过require('dotenv').config()import dotenv from 'dotenv' ,然后是dotenv.config()尝试了这个。 正如您将看到的,我尝试将 config 传递给绝对路径。 尝试控制台日志环境变量总是返回未定义。 我尝试检查dotenv.error ,正如您将看到的,并且条件不会触发。

我看到的都是未定义的。 就好像我的.env文件甚至不存在一样。

这是我当前状态的代码。 任何帮助,将不胜感激。

import express from "express";
import cors from "cors";
import multer from "multer";
import AWS, { PutObjectCommandOutput, S3, S3ClientConfig } from "@aws-sdk/client-s3";
import { createReadStream } from "fs";
import path from 'path';

const dotenvAbsolutePath = path.join(__dirname, '.env')

const app = express();
const port = 5000;
// require('dotenv').config();
const dotenv = require('dotenv').config({
  path: dotenvAbsolutePath,
});
if (dotenv.error) {
  console.log(`DOTENV ERROR: ${dotenv.error.message}`);
  throw dotenv.error;
}

const keys = {
  key: process.env.AWS_ACCESS_KEY_ID,
  secret: process.env.AWS_SECRET_KEY,
  region: process.env.AWS_REGION
};
console.log(dotenv);

const upload = multer({
  storage: multer.diskStorage({ destination: "./tmp" }),
});

const s3 = new S3({
  credentials: { accessKeyId: keys.key!, secretAccessKey: keys.secret! },
  region: keys.region!
});

app.use(cors());

app.post("/", upload.single("pdf_upload"), async (req, res) => {
  let fileName: string | undefined;
  // let fileBuffer: Buffer | undefined;
  let uploadResponse: PutObjectCommandOutput | undefined;

  if (req.file) {
    fileName = req.file.originalname;
    // fileBuffer = req.file.buffer
    console.log("HTTP Request Received");
    const fileReadStream = createReadStream(req.file!.path).on(
      "ready",
      async () => {
        try {
          console.log("Stream is Readable");
          console.log(fileReadStream.bytesRead);
          uploadResponse = await s3.putObject({
            Bucket: "fiberpunch-test",
            Key: fileName,
            Body: fileReadStream,
          });
          res.header("Access-Control-Allow-Origin", "*");
          res
            .send({ file: { ETag: uploadResponse.ETag, Key: fileName } })
            .status(200);
        } catch (err: any) {
          console.log("Upload Error: ", err.message);
          res.sendStatus(500);
          console.log(fileReadStream.bytesRead);
        }
      }
    );
  }
});

try {
  app.listen(port);
  console.log(`listening at port ${port}`);
} catch (err) {
  console.log("ERROR SETTING UP SERVER");
}

我认为您需要使用process.env来访问您的 env 变量。 尝试记录process.env.AWS_ACCESS_KEY_ID

好吧,我想通了。 首先,我在打字稿工作,忘了编译。 其次,.env 文件的绝对路径不正确。 在我这样做之后,环境变量拉得很好。

不过,我遇到了一个新错误:

Upload Error:  The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

如果我无法解决这个问题,我会发布另一个问题。 谢谢大家。

如果您在 .env 文件中使用 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY,则不必再次使用它们来创建 S3 对象。 AWS 自动识别这些密钥并将它们用于 S3 对象创建。 您只需要 region 即可创建 S3 对象。

 const s3 = new S3({ region: 'your region' });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM