server.js
const dotenv = require("dotenv");
const connectDatabase = require("./config/database");
const cloudinary = require("cloudinary");
// Handling uncaught errors
process.on("uncaughtException", (err) => {
console.log(`Error: $(err.message)`);
console.log("Shutting down server due to uncaught exception");
process.exit(1);
});
//config
dotenv.config({ path: "backend/config/config.env" });
//connecting to database
connectDatabase();
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const server = app.listen(process.env.PORT, () => {
console.log(`server is working on ${process.env.PORT}`);
});
//unhandled promise rejection
process.on("unhandledRejection", (err) => {
console.log(`Error: ${err.message}`);
console.log("Shutting down server due to unhandled promise rejection");
server.close(() => {
process.exit(1);
});
});
databse.js
const { connect } = require("net");
const connectDatabase = () => {
mongoose
.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((data) => {
console.log(`Mongodb connected with server ${data.connection.host}`);
});
};
module.exports = connectDatabase;
config.env
PORT=4000
DB_URI = "mongodb://localhost:27017/Ecommerce"
process.env.PORT is coming undefined instead of 4000. The same problem is coming for DB_URI and other process.env variables. If I write 4000 instead of process.env.PORT and "mongodb://localhost:27017/Ecommerce" instead of process.env.DB_URI it works fine. Below is the Error in my terminal.
server is working on undefined Error: The uri
parameter to openUri()
must be a string, got "undefined". Make sure the first parameter to mongoose.connect()
or mongoose.createConnection()
is a string. Shutting down server due to unhandled promise rejection
How can I resolve this issue?
Don't set these kind path: "backend/config/config.env"
of a path into your code: it depends on the process.cwd()
and it may change based on where you run your node.js command. It is not deterministic at all.
Use relative path to the server.js
instead:
const path = require('path')
dotenv.config({ path: path.join(__dirname, "./config/config.env") });
I assume your directory tree is:
/backend
- server.js
- /config
- config.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.