简体   繁体   English

ReferenceError: require 没有使用 require(“dotenv”).config() 定义;

[英]ReferenceError: require is not defined using require(“dotenv”).config();

For some reason i am having this error "ReferenceError: require is not defined" and i cant figure out why?.出于某种原因,我遇到了这个错误“ReferenceError:require is not defined”,我不知道为什么? Has anyone got an idea how i can fix this?有谁知道我该如何解决这个问题? i am trying to connect my e-commerce website to mongodb我正在尝试将我的电子商务网站连接到 mongodb

here's the code这是代码

.env file .env 文件

PORT=5000
MONGO_URL = mongodb+srv://nashmaj:frzw14qa@cluster0.52b6h.mongodb.net/e-commerce-webapp?retryWrites=true&w=majority

server.js file server.js 文件

require("dotenv").config();
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser');
// const { Console } = require('console');
const PORT = process.env.PORT || 5000

app.use(express.json())
app.use(cookieParser())
app.use(cors)
app.use(fileUpload({
    useTempFiles: true
}))
//connect to db

const URL = process.env.MONGO_URL
mongoose.connect({
    useCreateIndex: true, 
    useFindAndModify: false,
    useUnifiedTopology:true
}, err=> {
        if (err) throw err;
        console.log('Connected to Mongo DB')
})

app.get('/', (req, res) => { 
    res.json({msg: "Welcome"})
})

app.listen(PORT, () => { 
    console.log('Server is running on port', PORT)
})

You can check if you have configured node to use ES Modules.您可以检查您是否已将节点配置为使用 ES 模块。 This is in package.json这是在 package.json

"type": "module", “类型”:“模块”,

Remove this line and check again.删除此行并再次检查。

Remember that having "type": "module"you cannot use require and instead you need to use import syntax.请记住,拥有 "type": "module" 您不能使用 require 而是需要使用 import 语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM