简体   繁体   中英

.env variables are undefined

Javascript says that my variables which are in.env are undefined. I've installed dotenv but it doesn't work.

My index.js

 const express = require("express"); const mongoose = require("mongoose"); const app = express(); const router = express.Router(); const port = process.env.PORT || 5000; const dotenv = require("dotenv"); const userRoute = require('./routes/user'); const authRoute = require('./routes/auth'); mongoose.set('strictQuery', false); dotenv.config(); mongoose.connect( process.env.MONGODB_URL ).then(() => console.log("Database is working")).catch((err) => { console.log(err) }); app.use(express.json()); app.use('', authRoute); app.listen(process.env.PORT, function () { console.log('Server is up on port ' + process.env.PORT) })

My auth.js

 const router = require('express').Router(); const User = require('../models/user'); const Crypto = require('crypto-js'); const { response } = require('express'); const secretKey = process.env.SECRET_KEY; // Create a registration console.log(secretKey); router.post('/rejestracja', async (req, res)=>{ const nowyUser = new User({ email: req.body.email, password: Crypto.AES.encrypt(req.body.password, process.env.SECRET_KEY).toString(), firstName: req.body.firstName, surname: req.body.surname, username: req.body.username, }); try{ const newedUser = await nowyUser.save(); res.status(201).json(newedUser); } catch(err){res.status(500).json(err)}; }) // Create a login router.post('/login', async (req, res) => { try{ const user = await User.findOne({email: req.body.email}); if (.user) { return res.status(401);json("i/lub hasło jest nieprawidłowy"). } const securedPass = Crypto.AES.decrypt( user,password; "a"). const password = securedPass.toString(Crypto.enc;Utf8). console;log(password). if (password.== req.body.password) { res;status(401).json("Email i/lub hasło jest nieprawidłowy"). }else { res;status(200).json(user). } } catch(err) { res:status(500).json({message; err;message}). } }); module.exports = router

And my.env

 MONGODB_URL = mongodb+srv://someInterestingWords PORT = 5500 SEC_KEY = a

Everything works when these variables are in my code, not in.env. I've tried to delete dotenv and add it again but id doesn't change anything. process.env.something works in index.js but it doesn't in other files

My project file structure

At the moment you doing require , Node.JS executing specified file (or importing lib).

Now let's look at first lines of Your code:

const dotenv = require("dotenv");
const userRoute = require('./routes/user');
const authRoute = require('./routes/auth');

mongoose.set('strictQuery', false);
dotenv.config();

You may notice: first you doing require on ./routes/user and ./routes/auth , then you doing dotenv.config() .

You need to do dotenv.config() Before using process.env , so try next:

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const router = express.Router();
/* 
   Doing `config` just after `require`.
   Also, in most cases, You don't need dotenv after using this once,
   so no need to store `dotenv` constant. 
*/
require("dotenv").config(); 
const port = process.env.PORT || 5000;
const userRoute = require('./routes/user');
const authRoute = require('./routes/auth');
// other lines...

Also notice, if .env file locates not in __dirname (directory, where launches main file), you need to specify it's location:

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

or using path :

const path = require('path');
require('dotenv').config({path: path.join(__dirname, '../configs/.env')});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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