express - Can't connect to MongoDB with mongoose after installing package - Stack Overflow

I setup a MongoDB cluster using MongoDB atlas. After this I created an express app by running the npm i

I setup a MongoDB cluster using MongoDB atlas. After this I created an express app by running the npm init -y.

I then installed some packages and set the scripts. Here is my package.json:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon src/index.js",
    "start": "node src/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.1",
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.21.0",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.8.1",
    "multer": "^1.4.5-lts.1",
    "nodemon": "^3.1.7"
  }
}

After setting this up I managed to connect to MongoDB using mongoose.

Then I ran npm i axios and I got the following error when I ran npm run dev:

Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: /

At this moment I have enabled allow access from anywhere on my MongoDB cluster. So I do not know what is happening.

Here is my index.js:

require('dotenv').config();

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

app.use(express.json())

app.use(cors({
    origin: '*',
    credentials: true
}));

app.use(bodyParser.json());

mongoose.connect(process.env.MONGODB_URI);

mongoose.connection.on('connected', () => {
    console.log('Connected to MongoDB');
})

mongoose.connection.on('error', (err) => {
    console.log('Error connecting to MongoDB', err);
});

app.get('/', (req, res) => {
    res.send('API');
});

app.listen(process.env.PORT, () => {
    console.log(`API listening at http://localhost:${process.env.PORT}`);
});

module.exports = app;

I tried testing this with other packages too, but it happens everytime I install ANY package.

Any help would be appreciated!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745622555a4636609.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信