issue: Router.use requires a middleware function but got a obj - node.js

i have looked at all the other solutions around and I still cant seem to fix it
here is my file structure and my home.js where I have my routing which I moved from my routes.js file
i have already tried adding module.exports = router to the bottom of my .js files 1

You must register your router in app.js
More about routes
const homeRouter = require('./web/home');
app.use('/home', homeRouter );

Related

Nodjs swagger auto gen integration

I need to develop an API using NodeJS and also need to develop documentation for API also. I integrated with swagger auto-gen for swagger.json creation. But the swagger.json not generating properly if I used routes.js as below
var express = require('express');
module.exports = function(app) {
var userController = require('../controller/userController');
var apiRouter = express.Router();
var routerV1 = express.Router();
var routerV2 = express.Router();
app.use('/admin', apiRouter);
apiRouter.use("/v1", routerV1);
apiRouter.use("/v2", routerV2);
routerV1.route('/users').get(userController.getUsersV1);
routerV2.route('/users').get(userController.getUsersV2);
}
and also mapped these routes.js in swagger.js
Please suggest the best way to generate swagger.js
Do we need to create routes file for all controller?
Version 2 of swagger-autogen added this feature. Previous versions don't recognize routes. In your case, the best way to generate the file swagger.js is:
file: swagger.js
const swaggerAutogen = require('swagger-autogen')();
const outputFile = './swagger_output.json';
const endpointsFiles = ['./routes.js']; // root file where the route starts.
swaggerAutogen(outputFile, endpointsFiles).then(() => {
require('./index.js'); // Your project's root file
})
Update your module to the latest version.
And run your project with: node swagger.js
And about the routes file for all controller, you don't need to implement it for each one, but it also depends on the structure of your code. If you have a root route file like the example, this is enough for all sub-routes to be scanned. I hope it helps you. Take a look at this example if you need to:
swagger-autogen using router

How to automatically include routes in ExpressJS

Let's say you always wanted to do certain prefixes on routes, such as /before and to pop that off after a certain line in your server.js file.
Here's an example
const express = require('express');
const App = express();
App.get('/before') //so here the route is '/before'
App.push('/after') //This is a made up method, but something like this has to exist...
App.get('/before') //And this route would be '/after/before'
App.pop(); //Another made up method
App.get('/before') //and this would be just "/before"
This isn't exactly the .push() and .pop() design, but it lets you accomplish the same goal of grouping routes under a common parent path without having to specific the common parent path on each route definition.
Express has the concept of a separate router. You define a bunch of routes that want to share a common parent path on a router. You then register each leaf path on the router and then register the whole router on the parent path.
Here's an example:
const express = require('express');
const app = express();
const routerA = express.Router();
// define routes on the router
routerA.get("/somePath1", ...);
routerA.get("/somePath2", ...);
routerA.get("/somePath3", ...);
// hook the router into the server at a particular path
app.use("/parentPath", routerA);
app.listen(80);
This registers three routes:
/parentPath/somePath1
/parentPath/somePath2
/parentPath/somePath3

What is the function of router(app) do in the following code?

Here are few lines of code.I did not understand their function.I have commented in the code the lines that I have not understood.
var express = require('express');
var app = express();
var router = require('./app/router'); //not understood
router(app); //not understood
It will be helpful I anyone can explain their function.
var router = require('./api/router'); //not understood
There is plenty of resources out there explaining this. See e.g. What is this Javascript "require"?
router(app); //not understood
router is a function returned by require('./api/router'). The function takes one parameter app.
What the router function does ? We can't know that as it is a proprietary code located in you filesystem in a ./api/router file.
require function is the easiest way to include modules that exist in separate files.
usage file:
var router = require('./app/router');
router(app);
router function take app as a parameter for their use.
support (/app/router.js) file:
export default function(app) {
// code stuff
}

Cannot set express.static from another module

This works
var express = require('express');
var app = express();
var request = require('request');
// initialize session, redis server will be used if it's running otherwise will store in memory
require('./config/session.js')(app, function () {
// configurations
require('./config/bodyparser.js')(app);
require('./config/cookieparser.js')(app);
require('./config/compression.js')(app);
//require('./config/other.js')(app, express);
app.use(express.static('./public', { /*maxAge: 86400000*/}));
app.listen(3000, function () { console.log('running...'); });
});
But if I uncomment require other.js and comment app.use it doesn't. Here is the other.js file.
module.exports = function (app, express)
{
app.use(express.static('../public', { /*maxAge: 86400000*/}));
return app;
}
Tried different relatives paths but all failed. Here is the project structure
-config
--other.js
-public
-app.js
The error I get is
Cannot GET /index.html
on my browser, no error in console.
The issue here is that when you require the other.js file, the relative path is using the cwd of app.js. The best way to avoid this (and avoid the hassle with relative paths) is to use path.resolve and the __dirname variable.
__dirname is a special Node.js variable that always equals the current working directory of the file it's in. So combined with path.resolve you can always be sure that no matter where the file is being require'd it uses the correct path.
In other.js:
var path = require('path');
....
app.use(express.static(path.resolve(__dirname, '../public')));
Or you could simply update other.js to use ./public but I believe the above is better practice as if you move the app.js or require other.js in a different folder it won't resolve correctly
Info on path.resolve here

Express adds slash at the end of url weirdly

I'm using Node.js and Express framework for developing a website. I faced weird misbehaviour with a url. When i click to related link url, url becomes "localhost:3000/images/" - a slash is added at the end as you can see. But when i change all 'images' to 'img' or else url becomes "localhost:3000/img" no slash added. Why router behaves like that? Codes written below. (I'm using Jade template Engine)
//bar.jade
li.nav-item
a.nav-link(href='images')
i.icon-camera
| Images
//end of bar.jade
//images.js (router)
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('images', { title: 'Express'});
});
module.exports = router;
//end of router .js
//app.js
var images =require('./routes/images');
........
........
app.use('/images',images);
//end of app.js
I think I know what's going on: you're also using the express.static() middleware, and in your public directory you have a directory called images/.
This middleware will generate redirects ending with a slash when you try to request a URL that matches a public directory (even when that directory is empty or matches another route).
To disable this behaviour, set the redirect option to false.
By default in express router “/foo” and “/foo/” are treated the same by the router. You can disable this behavior with strict: true option.
Express.Router documentation
var router = express.Router({strict: true});

Resources