Good guys,
I wrote the express API which works perfectly well when tested with POSTMAN but couldn't do same when i try to get a responds displayed on the browser. Would be glad to know where i went wrong from my code base.
Thanks.
My code base below:
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bdclRoutes = require('./routes/bdcl.routes');
mongoose.connect(process.env.MONGODB_URI, {
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
mongoose.connection.once('open', () => {
console.log('Connected to database successfully....')
}).on('error', () => {<br/>
console.log('Database connection failed.....')
});
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
// res.send('Welcome to BDCL student API')
});
app.use('/api/2020/bdcl_students/uploads', express.static('./uploads'));
app.use('/api/2020', bdclRoutes);
app.listen(process.env.PORT, () => {
console.log(`server started and app running at port ${process.env.PORT}`)
});
the code looks fine. Something might be blocking your port. Change your port number and try again.
Related
I am trying to connect MongoDB with my signup.js, but it's not connecting. I am unable to find the problem. How can I solve this?
Code of signup.js:
const express = require('express')
const app = express()
require("./db/mydb");
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(4000, () => {
console.log(`App listening on port 4000`)
})
Code of mydb.js:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydata",{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(()=>{
console.log("connection successful")
}).catch((e)=>{
console.log("Not connected")
})
Error:
App listening on port 4000
Not connected
If the last log statement is replaced with console.log(e), the output is:
MongoParseError: option usecreateindex is not supported
Here you have a simple example of how to connect MongoDB to Node.js using Express.js and Mongoose on localhost obviously:
File server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Express and Mongoose connection!");
});
// Connect to db
mongoose
.connect("mongodb://localhost:27017/test")
.then(() => {
// Listen for requests
app.listen(port, () => {
console.log(
`Connected to DB & Server is listening at http://127.0.0.1:${port}`
);
});
})
.catch((error) => {
console.log(error);
});
And as we can read in the Mongoose documentation → no more deprecation warning options
useNewUrlParser, useUnifiedTopology, useFindAndModify, and
useCreateIndex are no longer supported options. Mongoose 6 always
behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex
are true, and useFindAndModify is false. Please remove these options
from your code.
It was tested with: "express": "^4.18.1", "mongoose": "^6.6.5"
I am following a tutorial online to make a simple CRUD node/express/mongo application. I can get this code to connect to the data base fine, but when I try to submit a quote to be added to the database, the console simply logs the data I've entered, and the data never actually gets added to the database. If anyone could help me to understand why this isn't working, I'd appreciate it.
A possible issue may be, in MongoDB atlas my project is called testeru, my database is called test, and my collection is called quotes. I'm not sure if I improperly referenced this data?
I am running this on local host and I did whitelist my IP address in Atlas.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
//mongodb
const MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb+srv://OBSCURED:OBSCURED#cluster0.izcbs.mongodb.net/test?retryWrites=true&w=majority', { useUnifiedTopology: true })
.then(client => {
console.log('Connected to Database')
const db = client.db('test')
const quotesCollection = db.collection('quotes')
// app.use{}
// app.get{}
app.post('/quotes', (req,res) => {
quotesCollection.insertOne(req.body)
.then(result => {
console.log(result)
})
.catch(error => console.error(error))
})
// app.listen{}
})
.catch(error => console.error(error))
//Body parser
app.use(bodyParser.urlencoded({extended:true}))
app.listen(3000, function() {
console.log('Listening on 3000');
})
//Get request:
app.get('/', (req,res) => {
res.sendFile(__dirname + '/index.html');
})
//CREATE
app.post('/quotes', (req, res) => {
console.log(req.body)
})
I always get "Listening at localhost" but the URL I put is from Mongo Atlas. And when I print the environment variable to the console I get it correctly. mongoose automatically ignores any url other than localhost.
I have tried to restart nodemon muiltiple times.
mongoose
.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log(process.env.DATABASE_URL); //prints the correct url but mongoose connects to localhost
console.log("mongo connected");
// logEntry.collection.drop();
})
.catch((error) => console.log(error.message));
validate the connection using the below mentioned code snippet.
const express = require('express');
const app = express();
const socketio = require('socket.io');
const mongoose = require('mongoose');
const expressServer = app.listen(3001);
const io = socketio(expressServer);
mongoose.connect('mongodb+srv://<UserName>:<Password>#democluster0.abcde.mongodb.net?retryWrites=true&w=majority');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
mongoose.connection.db.listCollections().toArray(function (err, names) {
console.log(names);
});
})
Refer the below link to gain the URL for the same..
https://docs.atlas.mongodb.com/tutorial/connect-to-your-cluster/
It shows no error at all. Even cosole shows the database is connected. But it is not showing the data. When I go to http://localhost:5000/tasks it shows
Cannot GET /tasks
what am I missing here?
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const MongoClient = require('mongodb').MongoClient;
require('dotenv').config()
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.vwtzw.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
const port =5000;
app.get('/', (req, res) => {
res.send('hello world!');
});
const client = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true });
client.connect(err => {
const tasksCollection = client.db("VolunteerNetwork").collection("tasks");
app.get('/tasks',(req, res) => {
tasksCollection.find({})
.toArray( ( err, documents) => {
res.send(documents);
console.log(documents);
console.log('database connected');
})
})
});
app.listen(port);
after I run it shows -
undefined
database connected
mongo database name: VolunteerNetwork.tasks
the get route is inside the connect method - try reorganizing the code so that you open the connection when a request is made
const MongoClient = require('mongodb').MongoClient;
const uri = `mongodb://localhost:27017`;
const client = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true });
router.get('/tasks',(req, res) => {
client.connect(err => {
const tasksCollection = client.db("VolunteerNetwork").collection("tasks");
tasksCollection.find({})
.toArray( ( err, documents) => {
res.send(documents);
console.log('database connected');
console.log(documents);
})
})
});
The code works perfectly fine. It is an accurate approach.
My mistake was I did not give access to the username to edit/read the database in MongoDB. Giving the privilege made the work done.
I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then the browser shows a message:
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
Here is my app.js:
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());
//const userRouter = require('./routes/user');
//app.use('/user', userRouter);
const startApp = async () => {
try {
await mongoose.connect('mongodb+srv://username:pass#cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
{ useUnifiedTopology: true,useNewUrlParser: true });
console.log(`successfully connected to database`);
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server runnin at ${port}`);
});
} catch (error) {
console.log(error.message)
}
}
startApp();
app.get('/', (req, res) => {
console.log("I am in the root");
res.send("hello World");
})
Why server is not responding from the browser?
try
app.use(cookieParser())
instead of
app.use(cookieParser)
Reference
I had the same problem db is connected but not able to send data. it looks weird but it works for me.
Add a new database user with new password, use the new userName and passw to connect your mongoodb
this is the exact like to add new database user
here is my db connection may it helps you too
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('connected to database'))
app.use(express.json())