Mongoose schema not displaying when I get request in postman - node.js

Here is my router in app.js
const infoRouter = require('./routes/infoRoutes');
const userRouter = require('./routes/userRoutes');
const app = express();
// routes
app.use('api/v1/informations', infoRouter);
app.use('/api/v1/users', userRouter);
module.exports = app;
Here is my infoRoutes.js
const express = require('express');
const infoController = require('../controllers/infoController');
const router = express.Router();
router
.route('/')
.get(infoController.getAllInfo)
.post(infoController.createInfo);
router
.route('/:id')
.get(infoController.getInfo)
.patch(infoController.updateInfo)
.delete(infoController.deleteInfo);
module.exports = router;
My moongoose schema is displaying in my mongoDB Compass. However, when I try to get request in postman. It says 404 not found.

Related

Why my incoming request not hitting my node.js(express ) server?

I have a node.js(express) app in which i have defined all my routes, controllers and all that.
customer.route.js
const express = require('express');
const Controller = require('../controllers/customer.controller');
const { customerValidationRules, validate } = require('../middlewares/request- validator.middleware');
const router = express.Router();
router.route('/create').post(customerValidationRules, validate, Controller.create);
module.exports = router;
my index.js file inside routes folder
const express = require('express');
const cors = require('cors');
const responseUtil = require('../helpers/response.helper');
const customerR = require('../routes/customer.route');
const router = express.Router();
router.use(cors());
router.use('/customers', customerR);
/** Returned when requested api url not found **/
router.use((req, res) => responseUtil.sendNotFound(res));
module.exports = router;
And my app.js(root file)
const routes = require('./routes');
const app = express();
app.use('/api/v1', routes);
Now when i am hitting my api via postman with this api url
http://localhost:3003/api/v1/customers/create
So it keeps going and none of my logs priting on the console it means that request is not coming to my server now. Can any one let me know what'st he issue in it.
Because routes in Express router are not chained.
If you have
app.use('/customers',customerRouter)
Then you have to in your customerRouter define the whole route:
router.post('/customers/create', yourPostStuff)

Browser showing "Cannot GET /api/posts/ " instead of "hello" from res.send('hello')

My index.js file:
//Dependencies
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const posts = require('./routes/api/posts.js');
//Configuration
const port = process.env.PORT || 5000;
//App object
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
//Main app
app.use('api/posts',posts);
//Starting server
app.listen(port,()=>{
console.log(`server running at ${port}`);
});
My Api file:
//Dependencies
const express = require('express');
const mongodb = require('mongodb');
//Mini app
const router = express.Router();
//Get post
router.get('/',(req,res)=>{
res.send('hello');
});
//Add post
//Delete post
module.exports = router;
I'm expecting to get "hello" in my browser but constantly getting "Cannot GET /api/posts/" in firefox and postman. What should I do now?
Correction :-
//Main app
app.use('/api/posts',posts);

not able to get collection from local mongoDB while using routes controllers and model separate files

// app.js file
const express = require('express');
const morgan = require('morgan');
const courseRouter = require('./routers/courseRouter');
const app = express();
/// middleware
app.use(morgan('dev'));
app.use(express.json());
app.use((req,res,next)=>{
console.log('from middle ware');
next();
});
app.use((req,res,next)=>{
console.log('from second middle ware');
next();
});
/// routes
app.use('/courses',courseRouter);
module.exports = app;
//////////////// server.js file
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const app = require('./app');
dotenv.config({path:"./config.env"});
mongoose.connect(process.env.DATABASE_LOCAL,{
useNewUrlParser:true,
useCreateIndex:true,
useFindAndModify:false,
useUnifiedTopology: true
}).then(con =>console.log(con.connections));
app.listen(3000,()=>{
console.log(` App running at port 3000`);
});
/////////////////courseRouter.js file
const express = require('express');
const courseController = require('./../controlers/courseController');
const router = express.Router();
router.
route('/courses').
get(courseController.getCourses);
module.exports = router;
//////// coursecontroller.js file
const Course = require('./../models/course.model');
exports.getCourses = async (req,res)=>{
try{
const courses = await Course.find({});
res.status(200).json({
status:'sucess',
data:{
courses
}
})
} catch (err){
console.log(err);
}
}
I'm trying to get simple get response from local mongoDB which is running at localhost:27017.
In there I have winrobot DB with collection courses which have one document.
So, my server is listening at port 3000, I have divided my routes , controllers and model according to MVC.
When I tried to get courses collection, I get "GET /courses 404 14.068 ms - 146" this morgan request log.but if I delete these controller and routes and implement that in app.js that works fine... so I want routes and controller in different files and still get courses collection.added the github repo of same code
You have this line:
app.use('/courses',courseRouter);
But then you are defining the router in the course file:
const router = express.Router();
router.
route('/courses').
get(courseController.getCourses);
Basically what ends up happening is you create a route that looks like:
/courses/courses/
You should change this:
router.
route('/').
get(courseController.getCourses);
Now your app will use the router you created properly.

app.use() requires a middleware function error

In a nodejs project I'm getting this error : 'app.use() requires a middleware function error at the line 7 of this file :
const Router = require('./route');
const express = require('express');
const app = express();
const port = 3001;
app.use(express.json());
app.use(Router);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
and I really don't get why I'm getting this error.
here are the routes files
const ProduitRouter = require('./produit');
const router = require("express").Router();
router.use("/produit", ProduitRouter);
module.exports = router;
const ProduitControleur = require("../controleur/produitDB");
const Router = require("express-promise-router");
const router = new Router;
//const router = require("express").Router();
router.get('/:id', ProduitControleur.getProduit);
router.post('/', ProduitControleur.postProduit);
router.patch('/', ProduitControleur.updateProduit);
router.delete('/', ProduitControleur.deleteProduit);
module.exports = router;
Try this.
In app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const http = require('http');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
require('./routes')(app); // path of file in which all your routes are defined.
module.exports = app;
in router file where all routes are define.
const express = require('express');
const router = express.Router();
const controller = require('path of controller');
router.post('/upload/file', verifyToken, controller .functionName);
module.exports = router;
As I can see, there is no imports for Router file

Multiple Routes in node express backend

I am new in node js and want to build an application in which they are multiple APIs and all are settled in routes folder but here is the problem when I tried to call the API in index.js(main file) its only take one route either userAPI or cleanerAPI.
As both APIs have different URL.
var mongoose = require ('mongoose');
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
const routerUser= require('./routes/userAPI')
mongoose.connect('mongodb://localhost:27017/Covid');
app.use(bodyParser.json());
app.use('/',router);
app.listen(4000,function(){
console.log("Server Running on 4000")
});
you can try this one also.
Main file(index.js or server.js)
const appRoutes = require('./Routes')
appRoutes(app)
Routes(index.js)
module.exports = app => {
app.use("/user", require('./users'));
app.use("/cleaner", require('./cleaner')); };
Routes(users.js)
const express = require('express');
const router = express.Router();
router.route('/list')
.post(function(req,res){......});
module.exports = router;

Resources