Answer the question
In order to leave comments, you need to log in
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:
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}`);
})
Answer the question
In order to leave comments, you need to log in
If I saw it correctly, the files are like this:
, and by default dotenv searches .env
in the current directory, if not reassigned, judging by the description .
I will assume that it index.js
was launched from ./client
, but server.js
, say, from the folder where it is located.
UPD Spoiler: .env
I 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 questionAsk a Question
731 491 924 answers to any question