How to fix routes in node js not working? - node.js

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/

Related

Why wont json from mongodb show up on localhost:5000?

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}`)
})

my function does not execute by the router

I have a router and it should execute my function when the user wants to access /matches URL, but it doesn't
this is my controller that my function is wroten in there
const matchModel = require(`./../models/matchModel`);
//This function will get matches
exports.getMatches = async (req, res) => {
const matches = await matchModel.find();
res.status(200).json({
status: "success",
results: matches.length,
data: {
matches,
},
});
};
this is my route handler that should execute the function in the controller
const express = require("express");
const matchController = require(`./../controllers/matchController`);
const router = express.Router();
router.route("/matches").get(matchController.getMatches);
module.exports = router;
and this is my app file that adds URLs to middleware
const express = require("express");
const matchRouter = require(`./routes/matchRoutes`);
const app = express();
app.use(express.json());
//importing routers
app.use("/matches", matchRouter);
module.exports = app;
and after all, I run this server.js file to run my app
const mongoose = require("mongoose");
const dotenv = require("dotenv");
//setting up dotenv setting and
dotenv.config({ path: "./config.env" });
const conString = process.env.DATABASE_CON_STRING;
const port = process.env.PORT;
const app = require(`./app`);
mongoose
.connect(conString, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then(() => {
console.log("connection to DB has been established successfully!");
});
app.listen(port, () => {
console.log("server is running...");
});
You are loading the router under /matches
app.use("/matches", matchRouter);
Then you are loading the /matches route under that router
router.route("/matches").get(matchController.getMatches);
That is going to make the route /matches/matches.
You probably want it to be router.route(''). This will be the index route under the /matches router.

Why I Can not get data from mongodb database?

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.

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

API Route for retrieving a MongoDB collection

I'm trying to retrieve data from my mongo database. The problem occurs when I try to do the get route in my API. The error I get is: SchemeName.collection is not a function.
Here is my API in routes/api/tejidos
const express = require("express");
const router = express.Router();
const Equipo = require("../../../models/Equipo");
router.post("/crear", (req, res) => {
// Form validation
const newEquipo = new Equipo({
nombre: req.body.nombre,
marca: req.body.marca,
modelo: req.body.modelo,
serial: req.body.serial,
proveedor: req.body.proveedor,
estado: req.body.estado,
zona: req.body.zona,
fechaCompra: req.body.fechaCompra,
tiempoGarantia: req.body.tiempoGarantia,
guiaUsoRapido:req.body.guiaUsoRapido
});
//if (err) throw err
newEquipo
.save()
.then(equipo=>res.json(equipo))
.catch(err => console.log(err));
});
router.get('/leer', function(req, res) {
const equipos = Equipo.collection("equipos")
res.json({
equipos: equipos
});
});
module.exports = router;
And this is my server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const equipos = require("./routes/api/tejidos/equipos");
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/tejidos/equipos", equipos);
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
app.listen(port, () => console.log(`Server up and running... ${port} !`));
I need to retrieve data in my collection (the ones I created with the post method) from the database when I use the GET method in Postman at http://localhost:5000/api/tejidos/equipos/leer
Also, I will appreciate any documentation that you recommend.
Simply use find method:
router.get('/leer', async (req, res) => {
const equipos = await Equipo.find();
res.json({ equipos });
});
And here is the helpful documentation for making queries with mongoose

Resources