skip to Main Content

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 = "mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority&appName=app";
const PORT = 4000;
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_URI = mongodb+srv://admin:[email protected]/? 
retryWrites=true&w=majority&appName=app;
PORT = 4000;

My .env file also at root directory
I also try to make MONGO_URI 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.

2

Answers


  1. Chosen as BEST ANSWER

    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. Have an any idea to make it dynamic?


  2. It looks like a typo with the declarations. MONGO_URI is different from MONGO_URL.

    You can try declaring both MONGO_URI and MONGO_URL variables in your .env file if you have a tendency to use both variables, even though this is not a good practice.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search