I want to use .env variables for my server-side but index.js can see .env but does not run mongo properly. I can log .env variables from index.js also if i define port and url statically in index.js everything going well.
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const cookieParser = require("cookie-parser");
const authRoute = require("./Routes/AuthRoute");
require("dotenv").config();
const {MONGO_URL,PORT} = process.env;
mongoose.connect(MONGO_URL, {
}).then(() => console.log("MongoDB is connected successfully"))
.catch((err) => console.error(err));
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
app.use(
cors({
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
}));
app.use(cookieParser());
app.use(express.json());
app.use("/", authRoute);
MONGO_URL=mongodb+srv://admin:admin@app.mcv3k.mongodb.net/?
retryWrites=true&w=majority&appName=app;
PORT=4000;
My .env file also at root directory I also try to make MONGO_URL to string in .env but it doesn't worked.
I want to use mongo url dynamically via .env but i couldn't figure it out.
I just solved the problem. The problem was Express 4.x , now treats app.listen()
as an asynchronous operation, so listener.address()
will only return data inside of app.listen()
's callback. If I declare port statically, code going well but it is also not good usage because it still static.