P
P
prolina2019-06-18 16:26:36
Node.js
prolina, 2019-06-18 16:26:36

Why are environment variables undefined?

There is an .env file containing variables like this: REACT_APP_EMAIL = email REACT_APP_PASS = password
When these variables are called, they are undefined.
Project structure:
5d08e5e74f591018359630.png
Calling variables in server.js (using dotenv)

const dotenv = require('dotenv');
dotenv.config();

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');

const app = express();


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/contacts', (req, res) => {
  console.log(req.body);
  console.log(process.env)
    nodemailer.createTestAccount((err, account) => {
        const htmlEmail = `
        <h3>Contact details</h3>
        <ul>
        <li>Name: ${req.body.name}</li>
        <li>Email: ${req.body.email}</li>
        </ul>
        <h3>Message</h3>
        <p>${req.body.message}</p>
        `;
        let transporter = nodemailer.createTransport({
            service: 'gmail',
            host: 'smtp.gmail.com',
            port: 587,
            secure: true,
            requireTLS: true,
            auth: {
                user: process.env.REACT_APP_EMAIL,
                pass: process.env.REACT_APP_PASS
            }
        })



        transporter.verify(function(error, success) {
            if (error) {
              console.log(error);
            } else {
              console.log("Server is ready to take our messages");
            }
          });
        let mailOptions = {
            from: '',
            to: '[email protected]',
            subject: 'New message',
            text: req.body.message,
            html: htmlEmail
        }
        transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                return console.log(err)
            }


            console.log('Message sent: %s', info.message)
            // console.log('Message URL: %s', nodemailer.getTestMessageUrl(info))
        })
    })
})

const PORT = process.env.PORT || 3001;

if (process.env.NODE_ENV === 'production') {
    // Serve any static files
    app.use(express.static(path.join(__dirname, 'client/build')));

    // Handle React routing, return all requests to React app
    app.get('*', function(req, res) {
      res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
    });
  }

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);

})

At the same time, if you look in the console in the index.js file (which is in the src folder), then the variables are displayed with the desired value
5d08e63710e3b623280428.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Shokhrov, 2019-06-18
@prolina

If I saw it correctly, the files are like this:
, and by default dotenv searches .envin the current directory, if not reassigned, judging by the description .
I will assume that it index.jswas launched from ./client, but server.js, say, from the folder where it is located.
UPD Spoiler: .envI was not in CWD, it helped to indicate the path to it throughdotenv.config({ path: … })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question