Node declaring express many files difference? - node.js

my English not very well but
My question is:
in this file
index.js
const express = require('express');
const app = express();
app.use(require('./routes/index.js'));
app.listen(3000);
routes/index
const express = require('express');
const app = express();
app.get(....
module.exports = app;
because I have to declare app again, is it necessary to create or instantiate express multiple times in multiple files?
what is the difference between app = express() in index.js and app = express() in routes/index.js
thanks

I am assuming that you are trying to implement routing in your Node.js application. If I am right then correct code of
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', ...
module.exports = router;
As you can see in above code that you don’t need to reinitialize the app again into the index.js. Instead you have to initialize the router.

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)

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;

How do we modularize files and then use in firebase cloud functions when using expressjs

I am using express in firebase cloud functions.
So my index.js needs to be moularized and split into different files.
What is the best way to do it.
I know that there is a SO post to how we can modularize nodejs apps, i just want to know how we could do the same if we use express.
test.js
var express = require('express');
var router = express.Router();
router.get('/test', function (req, res) {
res.json(200, {'test': 'it works!'});
});
module.exports = router;
index.js
var test = require("./routes/test.js");
var other = require("./routes/other.js");
...
//all your code for creating app
...
app.use('/test', test);
app.use('/other', other);
can we do something like this in firebase cloud functions when using with nodejs
and then export them like below:
exports.app = functions.https.onRequest(app);
Or is there any correct way to do it in case of express.
Thanks
As mentioned in this link, you could add a express app in firebase.
And in order to modularize the app into different files and then manage seperately,
you do like below.
index.js
const express = require('express');
const homePageRoute = require('./homePageRoute');
const cors = require('cors')({
origin: true
});
const app = express();
app.use(cors);
app.use('/api/home', homePageRoute);
exports.app = functions.https.onRequest(app);
and in your homePageRoute file you do like below
homePageRoute.js
const express = require('express');
const router = express.Router();
router.get('/some-route', verifyToken, (req, res) => {
// code
});
module.exports = router;
This will help.

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;

NodeJS - Socket.io Connection to Routes

I am trying to connect socket.io to my routing system, but despite the multiple methods I have read about to achieve this, I'm not sure the best approach with my setup as I have three degrees of separation from my server file and the route file that requires the socket.io configuration. Should I pass it as a constructor argument?
I tried passing the argument //Routing app.use(controllers)(io);, but ran into an error with the router module, so I don't believe I'm setting it correctly.
Error: var search = 1 + req.url.indexOf('?'); TypeError: Cannot read property 'indexOf' of undefined
Here is my setup.
app.js:
var express = require('express');
var app = express();
//Port Setting
var port = process.env.PORT || 3000;
//Server Port
var server = app.listen(port);
//External Packages
var io = require('socket.io')(server);
var redisAdapter = require('socket.io-redis');
var controllers = require('./app/controllers/routes');
//Routing
app.use(controllers);
routes.js:
var express = require('express');
var router = express.Router();
router.use('/app', require('./app-routes'));
router.use('/api', require('./api-routes'));
module.exports = router;
app-routes.js (where I would like to configure socket.io):
var express = require('express');
var app = express();
var appRoutes = express.Router();
/*==== / ====*/
appRoutes.route('/')
.get(activityFeed.load)
.post(activityFeed.filter);

Resources