HOW DO I FIX "CANNOT GET" USING NODEJS MONGODB - node.js

I m testing a simple Get api with postman, but i am getting "cannot GET".
server.js (in the root folder)
```const express = require('express');
const mongoose = require('mongoose');
const items = require('./routes/api/items');
const app = express();
//body Parser middleware
app.use(express.json());
//Db config
const db = require('./config/keys').mongoURI;
//const db = "mongodb+srv://gkmm:123123123#cluster0-bo4ln.mongodb.net/test?retryWrites=true&w=majority"
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser:true, useUnifiedTopology: true})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server started on port ${port}`));
//Use routes
app.use('./routes/api/items.js', items);```
routes(root folder)/api/items.js
```const express = require('express')
const router = express.Router();
//Item Model
const Item = require('../../models/Item')
//#route GET api/items
//#des Get AAll Items
//access public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1})
.then(items => res.json(items));
});
module.exports = router; ```
Running into this error while trying to test my API, i checked my paths are correct, my database is connected. but i have no idea why is it returning 404 not found.

After looking through your code, # the line which you ask app to use your routes
//Use routes
/* You are telling the route to go through e.g. <yoururl>/./routes/api/items.js/
in order to reach your GET in items.js
*/
app.use('./routes/api/items.js', items);```
To resolve this issue you can edit your app.use to
app.use('/test', items) // test is just an example, you can change it to other keywords
Then to access your items GET route use "/test/"

Shouldn't app.use('./routes/api/items.js', items); be app.use('/api/items', items); ?

Related

How do you search for an entry by a specific field like name in a mongodb server using express?

This is an express server that interacts with a mongoDb server using mongoose.Here I want to search for a specific entry with a given name instead of using findbyid function in the /getCollege/:name route.
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// app.use(parser);
mongoose.connect('mongodb+srv://swapnil:abc#cluster0.ma46p.mongodb.net/db?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('connected to db') })
//
app.get('/', (req, res) => {
res.send('We are home');
})
app.get('/getCollege/:name',async (req,res) =>{
})
app.listen(3000);
Parameters variables such as :name are available through req.params, on your case: req.params.name. After getting the value you would something like:
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// your code
app.get('/getCollege/:name',async (req, res) =>{
try {
const document = await College.findOne({ name: req.params.name });
res.json(document);
} catch(error) {
// Handle the error here.
console.log(error);
}
});
// your code
Take a look at these reading materials as well:
1 - http://expressjs.com/en/guide/routing.html
2 - https://medium.com/weekly-webtips/9-best-practices-for-rest-api-design-7fb0b462099b

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/

nodejs express route resulting in error 404

The route is not working. I been looking for the cause and I can't find where the problem is. I keep on getting 404 error on postman with the server running.
Here is my server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB Config
const db = require ('./config/keys').mongoURI;
// Connect to Mongo
mongoose.connect(db, {useNewUrlParser: true} )
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
//Routes
app.use ('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Here is the file containing the routes. Is located at /routes/api
const express = require('express');
const router = express.Router();
// Item Model
const Item = require('../../models/Item');
// #route GET api/items
// #desc Get All Items
// #access Public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items));
});
module.exports = router;
File models/item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
404 status : Route Not found , the url you are trying that is not found
in your app js , add slash / before api
app.use('/api/items', items);
url will be :
http://localhost:5000/api/items
Please understand the basic routes first.
Here is https://expressjs.com/en/guide/routing.html
When you run app like that
http://localhost:3000
app is runnin exactly on this url. If you route somthing else like that "api/items" this means that
http://localhost:3000api/items.
So create any route firstly add a '/' and then it looks like
http://localhost:3000/api/items

Cannot GET /api/signup - Using Postman and mongodb

I am very new to mongoose and I made one signup api and while testing it using POSTMAN I'm getting these weird error as well when I refresh my http://localhost:8000/api/signup I get a message saying "Cannot GET /api/signup" and in my postman post request I am seeing an error message that says "Cannot POST /api/signup".
How would I get rid of these messages that are being displayed?
I am following a tutorial so I tried copying and pasting the code from the GitHub to make sure everything was perfect but I was still seeing these error messages.
My app.js file is:
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
require("dotenv").config();
// import routes
const userRoutes = require("./routes/user");
// app
const app = express();
// db
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log("DB Connected"));
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
// routes middleware
app.use('api', userRoutes);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
my routes/users.js file is:
const express = require("express");
const router = express.Router();
const { signup } = require("../controllers/user");
router.post("/signup", signup);
module.exports = router;
my controllers/users.js is:
const User = require("../models/user");
exports.signup = (req, res) => {
console.log("req.body", req.body);
const user = new User(req.body);
user.save((err, user) => {
if (err) {
return res.status(400).json({
error
});
}
res.json({
user
});
});
};
I am hoping to see a response in my browser that does not display an image that image that says Cannot GET api/signup and I am hoping that Postman is able to return data from my api
It means there is no corresponding router setting to /api/signup
I think router.post("/signup", signup); should be router.post("/api/signup", signup);
This should work fine on PostMan.
But the browser url is a get request, so the request would still fail. You will need to send the post request by javascript then.
For example, something like :
fetch('/api/signup', {
method: 'POST',
body: 'signup data here'
})
.then(response => response.json());
Please let me know if the error still exist.
There is a minor bug
app.use('api', userRoutes);
change to
app.use('/api', userRoutes);
My issue was that when I installed mongoDB locally I had not properly installed it and was not using a /data/db folder. I was able to fully uninstall my older version of mongoDB and reinstall everything following this youtube tutorial: https://www.youtube.com/watch?v=MIByvzueqHQ

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