Why wont json from mongodb show up on localhost:5000? - node.js

Im trying to configure/connect mongodb to express but when go to localhost:5000/contacts it doesnt show up
im thinking the problem is with the uri but i cant be sure. Maybe incorrect syntax? Tehre are no error messgaes so i dont think i see what the problem is
route file:
const router = require('express').Router()
let Contacts = require('../models/contacts.model')
router.route('/').get((req, res) => {
Contacts.find()
.then(contacts => res.json(contacts))
.catch(err => res.status(400).json('Error: ' + err))
});
router.route('/add').post((req, res) => {
const name = req.body.name;
const email = req.body.email;
const phone = Number(req.body.phone);
const newContact = new Contacts({
name,
email,
phone
})
newContact.save()
.then(() => {res.json('Contacts added!')})
.catch(err => res.status(400).json('Error: ' + err))
})
module.exports = router
and for the server js:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose')
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json())
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDb database connection established succesfully")
})
const contactsRouter = require('./routes/contacts');
app.use('/contacts', contactsRouter)
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})

Try this one the problem might be server was not created.
const http = require('http')
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose')
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json())
const server = http.createServer(app);
const uri = process.env.ATLAS_URI;
server.on('listening', () => {
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDb database connection established succesfully")
})
})
const contactsRouter = require('./routes/contacts');
app.use('/contacts', contactsRouter)
server.listen(port, () => {
console.log(`Server is running on port ${port}`)
})

Related

Postman: Connect ECONNREFUSED 127.0.0.1:5005

I have developed an API endpoint. It was working fine before. Unfortunately the project folder got corrupted (I recreated the files db.js and server.js). But now when I try to fetch data from API, I'm getting:
"connect ECONNREFUSED 127.0.0.1:5005"
The URL I'm using is localhost:
And my server is running on the same port i.e. 5005:
Can someone please elaborate what can be the problem? My hunch is that when I recreated the files I may have missed something:
db.js:
const mongoose = require('mongoose');
const userName = "myUsername"
const password = "myPassword"
const dbName = "comfyRooms"
const dbURL = `mongodb+srv://${userName}:${password}#mongo-cluster.damzf.mongodb.net/${dbName}?authSource=admin&replicaSet=atlas-s7z01e-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true`
mongoose.connect(dbURL, {useUnifiedTopology: true, useNewUrlParser: true})
let connection = mongoose.connection
connection.on('error', () => {
console.log('Unable to connect to MongoDB')
})
connection.on('connected', () => {
console.log("MongoDB connection established :)")
})
module.exports = mongoose
server.js
const express = require('express')
const app = express()
const dbConfig = require('./db')
const roomsRoute = require('./routes/roomsRoute')
app.use('/api/rooms', roomsRoute)
const port = process.env.PORT || 5005
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
roomsRoute.js:
const express = require('express');
const router = express.Router();
const Room = require('../models/rooms');
router.get('/getallrooms', async (req, res) => {
try {
const rooms = await Room.find({});
return res.send(rooms);
} catch (error) {
return res.status(400).json({message: error});
}
});
module.exports = router;
I have attached the important files. Please let me know if any other information is missing. Thanks!
You are not passing the port variable to the listen function, you are just logging it
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
This should work
app.listen(port, () => {
console.log("Node JS server listening on port " + port)
})

Mongo DB didn't connect with my node server

I'm new in node and mongo.
I'm trying to connect mongo db with my node server but this error appears.
Error:getaddrinfo ENOTFOUND locahost
[nodemon] app crashed - waiting for file changes before starting...
server.js
`const express = require('express');
require('colors');
const products = require('./data/products');
const dotenv = require('dotenv');
//dotenv config
dotenv.config();
const { connectDb } = require('./config/config')
connectDb();
const app = express();
app.get('/', (req, res) => {
res.send('<h1>Welcome to Node server</h1>')
})
app.get('/products', (req, res) => {
res.json(products);
})
app.get('/products/:id', (req, res) => {
const product = products.find(p => p.id === req.params.id);
res.json(product);
})
const PORT = 8080;
app.listen(process.env.PORT || PORT, () => {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${process.env.PORT}`.inverse.green)
})`
config.js
const mongoose = require('mongoose');
require('colors');
const connectDb = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
})
console.log(`MongoDB connected ${conn.connection.host}`.yellow)
} catch (error) {
console.error(`Error:${error.message}`.inverse.red);
process.exit(1);
}
};
module.exports = { connectDb }
.env
PORT = 8080
NODE_ENV = development
MONGO_URI = mongodb://locahost:27017/local

connectDB is not a function

Hi I'm new to coding currently trying to set up a connection to my server.
Getting an error message:
"TypeError: connectDB is not a function"
This is my db.js file
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
and this is my server.js file
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)
Looking for some assistance I'm really new to coding so please forgive me if I posted wrongly.
check this out:
You are exporting mongoose from the db.js file. Try exporting the function connectDB you just created.
// between brackets just in case you need to export something else, ok?
module.exports = { connectDB }
Then import it like this:
const { connectDB } = require('./config/db')
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
const express = require('express')
const server = express()
const dotenv = require('dotenv')
const { connectDB } = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)

Can not call API from backend mongodb

I'm trying to call my mongoDB API but it's giving me this error:
xhr.js:178 GET http://localhost:3000/api/products 404 (Not Found)
Here is how I call my API:
useEffect(() => {
const fetchItems = async () => {
setLoading(true);
const res = await axios.get("/api/products");
setProducts(res.data);
setLoading(false);
console.log(res.data)
};
document.title = `Shop - The Beuter`;
fetchItems();
}, [props]);
And here is my server.js:
const express = require("express"),
bodyParser = require('body-parser'),
app = express(),
cors = require("cors"),
port = process.env.PORT || 8000,
db = "beuter",
path = require("path"),
server = app.listen(port, () => console.log(`Listening to on port ${port}`));
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static('beuter/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
}
require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);
this is my database.config.js:
const mongoose = require("mongoose");
module.exports = (name) => {
mongoose
.connect(process.env.MONGODB_URI || `mongodb://localhost/${name}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => console.log(`Successfully connected to ${name}`))
.catch((err) => console.log(err));
};
How can I fix this problem?
Here is my github project if you want to look over my code:
https://github.com/nathannewyen/the-beuter

How to fix routes in node js not working?

Anyone can help me I am new to node js and I am stuck with this error it return 404 not found when I am trying to visit http://localhost:5000/api/items on my postman..
this is the file items.js
const express = require('express');
const router = express.Router();
//Items Model
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({date: -1})
.then(items => res.json(items))
});
router.post('/', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save().then(item => res.json(item));
});
module.exports = router;
this is the server.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
add a '/' before pathname in server.js
app.use('/api/items', items);
localhost:5000/api/items should work then
You need to make the following changes to your server.js
import your router module
const express = require('express');
const mongoose = require('mongoose');
const router = require('path of the router module');
const app = express();
app.use(express.json());
app.use(router); //to use your router
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('/api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
Try this:-
As I can see in the image of "vscode"
you have used router.get("/")
whereas in postman you are using URL for GET request as localhost:5000/api/items.
Either change your backend code to router.get("/api/items") or correct your postman request to localhost:5000/

Resources