In my Node.js project I am using router file that imports controller files that have actual implementation of the methods. Like below.
app.js
'use strict';
var express = require('express');
var app = express();
var apiRoutes = express.Router();
routes.mainApi(apiRoutes);
app.use('', apiRoutes);
apiRoutes
'use strict';
var controller = require('../controller/apiController');
var uploadController = require('../controller/uploadController');
var fileUpload = require('express-fileupload');
module.exports.mainApi = function (apiRouter) {
apiRouter.post('/login', controller.login);
}
apiController
exports.login = function (req, res) {
// My code for login
};
I know when a api request comes then first app.js is executed. It further sends the request to apiRoutes as I called it in file. In apiRoutes when it finds
apiRouts.post(./login,controller.login) then it calls login function from controller. But I want to know that I am not passing req and res parameters anywhere in the login function then how they are being passed. Basically how this type of calling works.
Thanks in advance.
this function controller.login
as a callback parameter of r.post('path', callback)
and when controller.login is actual called by callback(request, response )
you will get req and res
Related
we are using Node.js + Express as back-end for an Angular2 app. One of the modules of the back-end is responsible for the information gathering about products, based on barcode, which is a param for the Express router. Currently, we're facing an issue when adding a GET request route that does not use the barcode param.
The router file looks as follows:
'use strict';
const express = require('express');
const router = express.Router();
const prodCtrl = require('./controller');
const auth = require('../middlewares/authenticationBearer');
module.exports.init = function(app) {
router.param('barcode', prodCtrl.findById);
router.get('/products/:barcode', auth.bearer(), prodCtrl.getProduct);
router.post('/products/article', auth.bearer(), prodCtrl.getProductData);
router.get('/products/csv', auth.bearer(), prodCtrl.csv);
return router;
}
The problem is the /products/csv route. In its current position, calling the route gives a 404 error seemingly because the param barcode is expected, as the function prodCtrl.findById is called first. By moving this route before the /products/:barcode route like so:
'use strict';
const express = require('express');
const router = express.Router();
const prodCtrl = require('./controller');
const auth = require('../middlewares/authenticationBearer');
module.exports.init = function(app) {
router.param('barcode', prodCtrl.findById);
router.get('/products/csv', auth.bearer(), prodCtrl.csv);
router.get('/products/:barcode', auth.bearer(), prodCtrl.getProduct);
router.post('/products/article', auth.bearer(), prodCtrl.getProductData);
return router;
}
the code works fine. Is this a bug in Express? Or am I missing something here?
You should put '/products/:barcode' route after '/products/article' because it blocks the request to get to the article (the barcode param catch any suffix)
I am playing with node.js and I don't quite understand why something I set up is working in one instance but if I make a slight change it will not work in another instance.
in my app.js I have
app.use('/musicplayer', require('./routes/music/index'));
in my music\index.js I have
var express = require('express');
var router = express.Router();
router.use('/users', require('./users'));
module.exports = router;
in my users.js I have this - working version
var express = require('express');
var usersRouter = express.Router();
var sqllite3 = require('sqlite3').verbose();
usersRouter.get('/login', function(req, res, next) {
res.render('music/login', { title: 'Express' });
});
module.exports = usersRouter;
But I would like to encapsulate the routes I am defining into another function like this not working this just hangs the page.
Modified version of my users.js not working
var express = require('express');
var usersRouter = express.Router();
var sqllite3 = require('sqlite3').verbose();
var router = function () {
usersRouter.get('/login', function (req, res, next) {
res.render('music/login', {title: 'Express'});
});
return usersRouter;
}
module.exports = router;
In the console I can see it comes in tries the get and nevers gets routed I see this "GET /musicplayer/users/login - - ms - -".
I have even put a console.log right before the return in the anonymous function I created to know it is getting in there and that I am hooking the pathways up right from the parent routes. And I do hit that log action to the screen.
Any help or tips would be appreciated:)
PS in case you are wondering I am trying to separate out apps for different development work I want to play with. So that is why I am doing the sub routing with musicplayer/index.js instead of just putting everything in the app.js for declaring of my main routes.
Router.use() expects an instance of another Router. However your (non-working) module only returns a function.
Use this in your index.js to fix the issue:
router.use('/users', require('./users')());
I'm making a nodeJS module, and I want to use expressJS as a framework for it.
I'm trying to see, how I could go by, including a function inside and app.get(); and call it via another file, such as the actual app.
var express = require("express");
var app = express();
app.get("/", function (req, res) {
exports.type = function (text) {
console.log(req.ip);
console.log(text);
}
});
now when I use this, and i call it on the actual app like:
var web = require("directory_to_file");
var express = require("express");
var app = express();
var http = require("http").Server(app);
app.get("/", function (req, res) {
web.type("Hello, world");
});
http.listen(10022, function () {
console.log("server is up");
});
I get an error:
TypeError: Property 'type' of object #<Object> is not a function
anyone know a way to make it so I can call the function?
There are generally two things you want to export as a module - an API and a Middleware. The classic example of middleware is an authentication module. To do the middleware, just export the middleware. I tend to do a little more than that so I can configure the middleware later. Something along the lines of this:
module.exports = exports = function(config) {
// Do something with config here
return function(req, res, next) {
// your middleware here
};
};
You can then use your middleware in your main program like this:
var app = require('express')(),
mymodule = require('./mymodule');
var config = {}; // replace with whatever config you need
app.use(mymodule(config));
app.listen(process.env.PORT || 3000);
To implement an API, you will create a Router object, then attach your routes to the Router object. You can then "mount" your router in your main program. For example, you could have a file called 'myroutes.js' with the following contents:
var express = require('express'),
myroutes = express.Router();
myroutes.get('/foo', (req, res) => {
res.status(200).type('application/json').send({ myparam: 'foo' });
});
module.exports = exports = myroutes;
Have the following in your main program:
var app = require('express')(),
myroutes = require('./myroutes');
app.use('/api', require('./myroutes'));
app.listen(process.env.PORT || 3000);
Here, in 'myroutes.js', I'm defining a sub-route of /foo and then in the main program, I'm mounting that on /api - so I would access /api/foo to access that API.
In your directory_to_file you are only exporting on app.get('/') which will never be called.
You could add in your directory_to_file the following code
var express = require('express');
var router = express.Router();
router.get('/', function(req, server) {
console.log(req.ip);
});
module.exports = router;
And in your main file you could use app.use('/', web)
A short explanation:
You are creating a new express app / config in your directory_to_file file which won't be launched or used. So your app.get event won't be fired once.
That's why web.type is not a function. You are not exporting anything.
Use the way I provided. This is a commonly used method.
You could call the code I provided a "route". Create multiple routes / route files and include them in your main method.
Your code just looks confused. If I understand you correctly, what you are really trying to do (at least in Node/express terminology) is write your own middleware.
Express is designed with this in mind and it's pretty straightforward e.g.
ipLogger.js
module.exports = function(req, res, next) {
console.log(req.ip);
next();
}
app.js
var http = require("http")
, express = require("express");
, app = express()
, server = http.Server(app)
, ipLogger = require("./ipLogger.js");
app.use(ipLogger()); // log IP of all requests
// handle routes
server.listen(10022, function() {
console.log("server is up");
});
I'm building a web app with Express and Node and am trying to factor my routing so that I don't have hundreds of routes in the same file. This site serves different files within the projects directory, so I made a file in routes/ called projectRoutes.jsto handle the routing for project files:
var express = require('express');
module.exports = function() {
var functions = {}
functions.routeProject = function(req, res) {
res.render('pages/projects/' + req.params.string, function(err, html) {
if (err) {
res.send("Sorry! Page not found!");
} else {
res.send(html);
}
});
};
return functions;
}
Then, in my routes.js, I have this...
var projectRoutes = require("./projectRoutes");
router.get('/projects/:string', function(req, res) {
projectRoutes().routeProject(req, res);
});
Is there a better way to structure this functionality within projectRoutes.js? In other words, how can I configure projectRoutes.js so that I can write the follow line of code in index.js:
router.get('/projects/:string', projectRoutes.routeProject);
The above seems like the normal way to handle something like this, but currently the above line throws an error in Node that says the function is undefined.
Thanks for your help!
You should use the native express router, it was made to solve this exact problem! It essentially lets you create simplified nested routes in a modular way.
For each of your resources, you should separate out your routes into several modules named <yourResource>.js. Those modules would contain all of the routing code as well as any other configuration or necessary functions. Then you would attach them in index.js with:
var apiRoute = router.route('/api')
apiRoute.use('/< yourResource >', yourResourceRouter)
For example, if you had a resource bikes:
In index.js:
var apiRoute = router.route('/api')
, bikeRoutes = require('./bikes')
apiRoute.use('/bikes', bikeRoutes)
Then in bike.js:
var express = require('express')
, router = express.Router()
, bikeRoutes = router.route('/')
bikeRoutes.get(function (req, res) {
res.send('api GET request received')
});
module.exports = bikeRoutes
From there its easy to see that you can build many different resources and continually nest them.
A larger of example of connecting the routes in index.js would be:
var apiRoute = router.route('/api')
, bikeRoutes = require('./bikes')
, carRoutes = require('./cars')
, skateboardRoutes = require('./skateboards')
, rollerskateRoutes = require('./rollerskates')
// routes
apiRoute.use('/bikes', bikeRoutes)
apiRoute.use('/cars', carRoutes)
apiRoute.use('/skateboards', skateboardRoutes)
apiRoute.use('/rollerskates', rollerskateRoutes)
Each router would contain code similar to bikes.js. With this example its easy to see using express's router modularizes and makes your code base more manageable.
Another option is to use the Router object itself, instead of the Route object.
In Index.js:
//Load Routes
BikeRoutes = require('./routes/Bike.js');
CarRoutes = require('./routes/Car.js');
//Routers
var express = require('express');
var ApiRouter = express.Router();
var BikeRouter = express.Router();
var CarRouter = express.Router();
//Express App
var app = express();
//App Routes
ApiRouter.get('/Api', function(req, res){...});
ApiRouter.use('/', BikeRouter);
ApiRouter.use('/', CarRouter);
In Bike.js:
var express = require('express');
var router = express.Router();
router.get('/Bikes', function(req, res){...});
module.exports = router;
Similarly in Car.js
I've just started to play around with Expressjs and I'm wondering how to pass variables to mounted middleware/sub application. In the following example, I'd like the config object passed to my /blog/index
in app.js
var express = require('express');
var app = express();
//...
var config = {}
//...
app.use('/blog', require('./blog/index')
in /blog/index.js
var express = require('express');
app = module.exports = express();
app.use(express.static(...
app.get('/', function(req, res, next) {
//handle the req and res
}
Thanks,
I see two options here:
Since your blog app is an express application, you can use app.set and app.get. E.g.
blog = require('./blog/index');
blog.set('var1', value1);
blog.set('var2', value2);
...
app.use('/blog', blog);
And in blog/index.js use app.get('var1') to get the value of var1.
You can wrap the blog express application in another function that accepts configuration parameters (much like the static middleware accepts a directory name) and returns the configured application. Let me know if you want an example.
EDIT: Example for the 2nd option
app.js would look like this:
var blog = require('./blog/index');
...
var config = {};
app.use('/blog', blog(config));
and /blog/index.js like that:
var express = require('express')
module.exports = function(config) {
var app = express();
// configure the app and do some other stuffs here
// ...
return app;
}