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

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)

Related

Unable to Access Req.body (Nodejs Express)

I am new to Node.js and trying to make an API which would add a user into MongoDB database, my problem is I am Unable to access any properties of res & req in my controller. I tried searching for answer on SO but it seems the problem lies how you export the routes but the more I see the answers the more I get confused.
Here is part of my Server.js file,
const express = require("express");
const { readdirSync } = require("fs");
const dotenv = require("dotenv");
const app = express();
const mongoose = require("mongoose");
app.use(cors(options));
app.use(express.json());
This is how I am registering Routes,
readdirSync("./routes").map((r) => app.use("/", require("./routes/" + r))); //here route folder is being registered as a controller
Now in my Routes/User.js
const express = require("express");
const { register } = require("../controllers/user");
const router = express.Router();
router.get("/register", register);
module.exports = router;
In Controller/User.js
exports.register = async (req, res) => {
// here is the problem, when this controller is hit, i want to send response back
// like res.send("user added successfully") but I am unable to access req."send" or "body"
};
I have Tried using app.use(express.json()); answer on some forums but to no avail.

Mongoose schema not displaying when I get request in postman

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.

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;

App.route is not a function when accessing it in a controller function for express routing

I am trying to create a simple API using NodeJS.
I plan to separate the main api.js, route-definitions.js, route-logic.js in their own separate folders for them to be more structured and organized.
However, when I call app.route() in my route-definitions.js, it fails at compilation and saying that app.route is not a function.
server.js
var express = require('express')
var api = require("./api/api.js");
app = express();
port = process.env.PORT || 3000;
app.use('/', api);
app.listen(port);
api.js
var express = require('express');
var router = express.Router();
router.use('/read', require('./routes/route-definitions'));
module.exports = router;
route-definitions.js
'use strict';
module.exports = function(app) {
var operations = require('../controllers/route-logic.js')
//Route to check if a file with the same file name already exists
app.route('/getItems')
.post(operations.getItems);
}
When I try to run the API locally, and call /read/getItems, I get the error:
TypeError: app.route is not a function
What am I missing? I'm fairly new to Node and Express, but I know I'm not passing the app instance correctly or it is not set globally.
You can solve it by creating a child router in route-definitions.js
var router = require('express').Router();
var operations = require('../controllers/route-logic.js');
router.post('/getItems', operations.getItems);
module.exports = router;
In api.js you need to pass the router to the function you are exporting in route-definitions.js
var express = require('express');
var router = express.Router();
router.use('/read', require('./routes/route-definitions')(router));
module.exports = router;
You've used app in the route-definitions.js but looks like you forgot to pass it to that module.
Please have a look at below code:
var express = require('express');
var router = express.Router();
var app = express();
router.use('/read', require('./routes/route-definitions')(app));
module.exports = router;

Using modularized route throws a 404 error

I'm doing to some refactoring in my application and I don't understand why this case is failing.
index.js
const express = require('express');
const router = express.Router();
const models = require('../models');
const listRoute = require('./list');
router.use('/list', listRoute);
list.js
const express = require('express');
const router = express.Router();
const models = require('../models');
const sendListDataToView = (req, res, view) => {
// get data from backend and pass to template
}
router.route('/list/show/:id')
.get((req, res) => {
sendListDataToView(req, res, 'view-list')
})
router.route('/list/expand-records-forms/:id')
.get((req, res) => {
sendListDataToView(req, res, 'edit-list-records')
})
module.exports = router;
Trying to navigate to /list/show/3 throws a 404 error. However, if I move the definitions of these routes and sendListDataToView to index.js, the page loads fine. Is this because of the multiple router.routes?
I'm just going to wipe my original answer.
You need to create the app.
const express = require('express');
const app = express();
const models = require('../models');
const listRoute = require('./list');
app.use('/list', listRoute); // Using express now.
app.listen(8080); // starts server

Resources