.env返回多个文件的未定义

时间:2020-01-29 04:12:30

标签: node.js reactjs express npm environment-variables

我有两个使用 .env 的文件,都为变量返回undefined,我现在尝试为前端和后端都设置根.env,但仍然是。 env变量未加载。

在前端,我尝试测试的所有.env变量都未定义,我检查了其他人使用的代码,并根据建议进一步修改了该代码,但未定义...

enter image description here

前端有

import React from "react";
import axios from "axios";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import StripeCheckout from "react-stripe-checkout";

require('dotenv').config();


toast.configure();

const PaymentButton = ({ name, price, description }) => {

  console.log(process.env.PRIVATE_KEY);
  console.log(process.env.TESTING)

 const handleToken =   async (token, addresses) => {
    const response = await axios.post(
      "http://localhost:3000/checkout",
      { token, product: { name, price, description } }
    );

   const { status } = response.data;

   console.log("Response:", response.data);

    if (status === "success") {
      toast("Success! Check email for details", { type: "success" });
    } else {
      toast("Something went wrong", { type: "error" });
    }
  }

  return (
    <div className="container">
      <div className="product">
        <h1>{name}</h1>
        <h3>Product price:  ${price}</h3>
      </div>
      <StripeCheckout
        stripeKey= {process.env.PRIVATE_KEY}
        token={handleToken}
        amount={price * 100}
        name={name}
        // billingAddress
        // shippingAddress
      />
    </div>
  );
}


都返回未定义

我的.env文件


PRIVATE_KEY = pk_test_FAKERUr

TESTING = Hello

TEST_KEY = sk_test_FAKEHIHI8pGQt


在后端

require('dotenv').config();
const cors = require('cors');
const express = require('express');
const stripe = require('stripe')(process.env.TEST_KEY);
const uuid = require('uuid/v4');


const app = express();

app.use(express.json());
app.use(cors());



app.post('/checkout', async (req, res) => {

    }

    res.json({ error, status });
});


查看文件结构

enter image description here

1 个答案:

答案 0 :(得分:0)

确保您的.env如下所示:

PRIVATE_KEY = pk_teff23f23

TESTING = Hello

TEST_KEY = sk_test_f32f23f23f23  FAKE  Qt

您只需要在根应用中添加required('dotenv').config()server.jsapp.js

现在从您的服务器上,您可以像下面的代码那样进行操作:

// your dotenv in the first line
require('dotenv').config();
const cors = require('cors');
const express = require('express');
const stripe = require('stripe')(process.env.TEST_KEY);
const uuid = require('uuid/v4');


// console.log environment variable
console.log(process.env.PRIVATE_KEY);

确保第一行中的require('dotenv').config();确保.env文件与后端位于同一根目录。

?您的后端无法获取您的.env 的唯一原因是因为您的.env文件不在您的后端。 现在,将您的.env文件移到您的后端文件夹中。

我希望它能为您提供帮助。