NodeJS 为什么我的.env未定义,为什么它不工作?

hsgswve4  于 12个月前  发布在  Node.js
关注(0)|答案(2)|浏览(155)

我有问题的最后10行代码,我与一个. env。我已经添加了我的.env文件与MESSAGE_STYLE=。
但是,当使用npm start启动本地服务器时,我得到的是“hello json”消息的小写版本,而不是大写版本。
它还说我在根目录下的secret.env文件在那里,现在说A,不是U,因为未定义,idk我做了什么不同的,但是,我仍然得到我的输出:{“消息”:“Hello json”}
不是我所期待的:
{“消息”:“Hello json”}

输入:

let express = require('express');
let app = express();
require('dotenv').config();


app.use("/public", express.static(__dirname + "/public"))

app.get("/", (req, res) => {
    res.sendFile (__dirname + "/views/index.html");

})

app.get ("/json", (req, res) => {
    if ( process.env["MESSAGE_STYLE"] == "uppercase"){
        res.json({"mesage": "HELLO JSON"});
    } else {
         res.json({"message": "Hello json"});
    }
})

module.exports = app;
wgx48brx

wgx48brx1#

根据dotenv文档,默认情况下从.env文件加载环境变量。如果你想从自定义secret.env文件加载它们,你需要配置它:

require('dotenv').config({ path: 'secret.env' })
z0qdvdin

z0qdvdin2#

你能改变一下进口的顺序吗?
所以我们没有

let express = require('express');
let app = express();
require('dotenv').config();

你要做

require('dotenv').config(); // Make sure this is on the first line of your file
let express = require('express');
let app = express();

如果没有帮助,您也可以使用dotenv的调试模式

require('dotenv').config({ debug: true });

或者您也可以使用以下命令进行调试:

console.log(require('dotenv').config())

相关问题