Node.js 无法识别 .env 中的任何变量
Node.js can't recognise any variables in .env
我正在学习 fullstackopen.com 课程,我的 .env 文件似乎有问题,目前当我尝试连接到数据库时出现此错误:
error connecting to MongoDB 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.
我从检查以前的答案中发现 process.env 变量没有被 Node.js 正确读取大部分问题都是关于没有正确导入 dotenv 我的代码有这个所以我不知道'认为这可能是问题所在。我还将 .env 变量打印到控制台,但它是未定义的。我的 .env 文件也在项目的根目录中,所以我不认为它是。
我已经包含了我的 .env 文件和用于调用下面代码的文件。
.env 文件
MONGODB_URI='mongodb+srv://fullstackopen:<MyPasswordisHERE>@cluster0.brwcy.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
PORT=3001
note.js申请
require('dotenv').config()
const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('connecting to', url)
mongoose.connect(url)
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB', error.message)
})
const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean,
})
noteSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
module.exports = mongoose.model('Note', noteSchema)
index.js
require('dotenv').config()
const { request, application, response } = require('express')
const express = require('express')
const app = express()
const Note = require('./models/note')
app.use(express.json())
app.use(express.static('build'))
const cors = require('cors')
app.use(cors())
app.get('/', (request, response) => {
response.send('<h1>Hello World</h1>')
})
app.get('/api/notes/:id', (request, response) => {
const id = Number(request.params.id)
const note = notes.find(note => note.id === id)
if(note){
response.json(note)
}
else {
response.status(404).end()
}
})
app.get('/api/notes',(request, response) => {
Note.find({}).then(notes => {
console.log(response)
response.json(notes)
})
})
app.delete('/api/notes/:id', (request, response) => {
const id = Number(request.params.id)
notes = notes.filter( note => note.id !== id)
response.status(204).end()
})
const generateId = () => {
const maxId = notes.length > 0
? Math.max(...notes.map(n => n.id))
: 0
return maxId + 1
}
app.post('/api/notes', (request, response) => {
const body = request.body
if(!body.content){
return response.status(400).json({
error: 'content missing'
})
}
const note = {
content: body.content,
important: body.important || false,
date: new Date(),
id: generateId(),
}
notes = notes.concat(note)
response.json(note)
})
const unknownEndpoint = (request, response) => {
response.status(404).send({error: 'unknown endpoint'})
}
app.use(unknownEndpoint)
const PORT = process.env.PORT
app.listen(PORT, ()=> {
console.log(`Sever is running on port ${PORT}`)
})
我知道我在 note.js 和 index.js 中导入了 dotenv,原因是当我测试为什么 .env 没有被识别时,我检查了 note.js 文件 运行 仅使用下面的命令,但是在生产中导入仅在 index.js 中,所以这不是问题
node note.js
我的项目文件结构也包含在下面
. .. build .env .git .gitignore index.js models mongo.js node_modules package.json package-lock.json Procfile requests
确保您的 .env 在文件夹结构中。例如,如果您的 .env 在根文件夹中,但您试图从文件夹中加载它,请确保添加正确的路径:
require('dotenv').config({path: __dirname + '/.env' })
解决了问题,当使用 heroku 部署时,您必须配置配置变量以匹配 .env 中的环境变量
Whosebug 中的其他答案并不清楚如何执行此操作,我在下面概述了我采取的步骤。
- 转到“应用程序”>“设置”>“显示配置变量”
- 您将看到两个文本字段,一个标记为键,另一个标记为
其他值
- 对于密钥,使其等于您的环境变量的名称,对我来说是 MONGODB_URI
- 对于值字段,它应该等于您需要的环境变量,对我来说,它是 MongoDB Atlas 的 url。
我正在学习 fullstackopen.com 课程,我的 .env 文件似乎有问题,目前当我尝试连接到数据库时出现此错误:
error connecting to MongoDB 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.
我从检查以前的答案中发现 process.env 变量没有被 Node.js 正确读取大部分问题都是关于没有正确导入 dotenv 我的代码有这个所以我不知道'认为这可能是问题所在。我还将 .env 变量打印到控制台,但它是未定义的。我的 .env 文件也在项目的根目录中,所以我不认为它是。
我已经包含了我的 .env 文件和用于调用下面代码的文件。
.env 文件
MONGODB_URI='mongodb+srv://fullstackopen:<MyPasswordisHERE>@cluster0.brwcy.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
PORT=3001
note.js申请
require('dotenv').config()
const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('connecting to', url)
mongoose.connect(url)
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB', error.message)
})
const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean,
})
noteSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
module.exports = mongoose.model('Note', noteSchema)
index.js
require('dotenv').config()
const { request, application, response } = require('express')
const express = require('express')
const app = express()
const Note = require('./models/note')
app.use(express.json())
app.use(express.static('build'))
const cors = require('cors')
app.use(cors())
app.get('/', (request, response) => {
response.send('<h1>Hello World</h1>')
})
app.get('/api/notes/:id', (request, response) => {
const id = Number(request.params.id)
const note = notes.find(note => note.id === id)
if(note){
response.json(note)
}
else {
response.status(404).end()
}
})
app.get('/api/notes',(request, response) => {
Note.find({}).then(notes => {
console.log(response)
response.json(notes)
})
})
app.delete('/api/notes/:id', (request, response) => {
const id = Number(request.params.id)
notes = notes.filter( note => note.id !== id)
response.status(204).end()
})
const generateId = () => {
const maxId = notes.length > 0
? Math.max(...notes.map(n => n.id))
: 0
return maxId + 1
}
app.post('/api/notes', (request, response) => {
const body = request.body
if(!body.content){
return response.status(400).json({
error: 'content missing'
})
}
const note = {
content: body.content,
important: body.important || false,
date: new Date(),
id: generateId(),
}
notes = notes.concat(note)
response.json(note)
})
const unknownEndpoint = (request, response) => {
response.status(404).send({error: 'unknown endpoint'})
}
app.use(unknownEndpoint)
const PORT = process.env.PORT
app.listen(PORT, ()=> {
console.log(`Sever is running on port ${PORT}`)
})
我知道我在 note.js 和 index.js 中导入了 dotenv,原因是当我测试为什么 .env 没有被识别时,我检查了 note.js 文件 运行 仅使用下面的命令,但是在生产中导入仅在 index.js 中,所以这不是问题
node note.js
我的项目文件结构也包含在下面
. .. build .env .git .gitignore index.js models mongo.js node_modules package.json package-lock.json Procfile requests
确保您的 .env 在文件夹结构中。例如,如果您的 .env 在根文件夹中,但您试图从文件夹中加载它,请确保添加正确的路径:
require('dotenv').config({path: __dirname + '/.env' })
解决了问题,当使用 heroku 部署时,您必须配置配置变量以匹配 .env 中的环境变量
Whosebug 中的其他答案并不清楚如何执行此操作,我在下面概述了我采取的步骤。
- 转到“应用程序”>“设置”>“显示配置变量”
- 您将看到两个文本字段,一个标记为键,另一个标记为 其他值
- 对于密钥,使其等于您的环境变量的名称,对我来说是 MONGODB_URI
- 对于值字段,它应该等于您需要的环境变量,对我来说,它是 MongoDB Atlas 的 url。