[英]unable to access config variables
server.js服务器.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数据库.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配置.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. process.env.PORT 未定义而不是 4000。同样的问题也出现在 DB_URI 和其他 process.env 变量中。 If I write 4000 instead of process.env.PORT and "mongodb://localhost:27017/Ecommerce" instead of process.env.DB_URI it works fine.
如果我写 4000 而不是 process.env.PORT 和 "mongodb://localhost:27017/Ecommerce" 而不是 process.env.DB_URI 它工作正常。 Below is the Error in my terminal.
以下是我终端中的错误。
server is working on undefined Error: The uri
parameter to openUri()
must be a string, got "undefined".服务器正在处理未定义错误:
openUri()
的uri
参数必须是字符串,得到“未定义”。 Make sure the first parameter to mongoose.connect()
or mongoose.createConnection()
is a string.确保
mongoose.connect()
或mongoose.createConnection()
的第一个参数是一个字符串。 Shutting down server due to unhandled promise rejection由于未处理的 promise 拒绝而关闭服务器
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.不要在代码中设置这些
path: "backend/config/config.env"
:它取决于process.cwd()
,它可能会根据您运行 node.js 命令的位置而改变。 It is not deterministic at all.它根本不是确定性的。
Use relative path to the server.js
instead:改用
server.js
的相对路径:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.