【问题标题】:Node.js can't recognise any variables in .envNode.js 无法识别 .env 中的任何变量
【发布时间】:2022-01-22 04:01:30
【问题描述】:

我正在关注 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.

通过检查以前的答案,我发现 Node.js 没有正确读取 process.env 变量大多数问题都围绕着没有正确导入 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

【问题讨论】:

    标签: javascript node.js mongodb mongoose nosql


    【解决方案1】:

    确保您的 .env 在文件夹结构中。例如,如果您的 .env 位于根文件夹中,但您尝试从文件夹中加载它,请确保添加正确的路径:

    require('dotenv').config({path: __dirname + '/.env' })
    

    【讨论】:

    • 我确实尝试过这个,但它不会仍然适用于 index.js,因为 .env 和 index.js 都在根目录中。这里有点愚蠢的问题,但 __dirname 只是一个占位符吗?
    • 您在根文件夹中有所有这些文件吗?如果 index.js 在根目录中,则无需指定路径,因为 .env 在那里。
    • 是的,它们都在根目录下..
    • 奇怪。尝试在 = 例如 MONGODB_URI=mongodb+srv://fullstackopen:@cluster0.brwcy.mongodb.net/myFirstDatabase?retryWrites=true&w=majority 之后从 env 中删除 '。
    • 还是不行。
    【解决方案2】:

    解决了这个问题,使用 heroku 部署时,您必须配置配置变量以匹配 .env 中的环境变量

    StackOverflow 中的其他答案不太清楚如何执行此操作,我在下面概述了我采取的步骤。

    1. 转到应用程序 > 设置 > 显示配置变量
    2. 您将看到两个文本字段,一个是带标签的键,另一个是 其他价值
    3. 对于我来说,让它与环境变量的名称相同,它是 MONGODB_URI
    4. 对于 value 字段,它应该等于您需要的环境变量,对我来说它是 MongoDB Atlas 的 url。

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2018-12-15
      • 2021-01-06
      • 2019-11-03
      • 2020-07-17
      • 2018-03-18
      相关资源
      最近更新 更多