How are Express middleware chained? - node.js

I have the following in app.js
var app = require("express")();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(require("./routes/admin");
...
And in ./routes/admin.js:
var router = require("express").Router();
var bodyParser = require("body-parser");
router.use(bodyParser.json());
router.get("/", (req, res)=> { res.send("test"); });
...
module.exports = router;
The main app already has bodyParser as a middleware, and app uses admin as a route. Is the router.use(bodyParser.json()) statement required in admin.js if I want to use it in admin.js? Would a request be parsed in app.js before continuing to admin.js?

Related

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

body parser logging empty object in express router

for some reason I can see my req.body in my express server on my route
req body is [Object: null prototype] { '{"password":"xxxxxxxx"}': '' }
but when I log req.body.password (the object key) I get
req body is undefined
here's my index router for reference in my express app
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
const path = require('path');
/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {
console.log('req body is',req.body.password)
res.send("passconfirmed");
});
module.exports = router;
To access the content of the body, Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
You need to install a body-parser package.
npm i body-parser --save
Now import body-parser in your project.
It should be called before your defined route functions.
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser')
const path = require('path');
app.use(bodyParser.json());
app.use(bodyparser.urlencoded({ extended : true }));
/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {
console.log('req body is',req.body.password)
res.send("passconfirmed");
});
module.exports = router;
If you're using body-parser
You have to enable the body parser to work, before using parsed data in you routes.
In your main module where you import all your libs, you need to declare express to use body-parser middleware.
const express = require('express')
const bodyparser = require('body-parser')
const app = express()
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended : true }))
...
//here comes your routes
After including the bodyparser middleware you can use parsed data in your routes.
Notice that if you're using express version >= 4.16, body parser comes bundled with express. You just have to use change your code to:
const express = require('express')
const app = express()
app.use(express.json()); //this line activates the bodyparser middleware
app.use(express.urlencoded({ extended: true }));
Doing so you can safely remove body-parser package.

router redirect in express not working

I have 3 files
app
routes/index.js
routes/home.js
app.js
var express = require('express');
var app = express();
//require routes
var index = require('./routes/index.js')
var home = require('./routes/home.js')
app.set('port',3000)
app.set('view engine', 'pug')
app.use('/', index);
app.use('/home' , home);
//app.use('/routes',users);
app.listen(3000);
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
router.get('/' , function(req,res){
res.redirect('/home')
})
module.exports = router;
home.js
var express = require('express');
var router = express.Router();
router.get('/home' , function(req ,res){
res.send('Got request on home route')
})
module.exports = router;
This sends a cannot GET on HOME route.Strangely this works if i put both routes in one file.I think I am making a mistake while importing?

ExpressJS cannot get POST

The relevant part of my app.js is as follows
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var routes = require('./config/routes);
app.use('/', routes);
My route file is:
var express = require('express');
var router = express.Router();
var upgradesController = require('../../app/controllers/upgrades.server.controller');
// This should receive POST requests
router.post('/api/upgrades/device', upgradesController.create);
module.exports = router;
And finally my controller is
exports.create = function(req, res) {
res.send(req.body);
}
But this sends nothing. It's always an empty JSON value. I'm using PostMan for testing:
What is happening?
You're sending form-data, switch to x-www-form-urlencoded instead. You can also send "raw", and input valid JSON.

Using Express Router in routes.js

I am currently using routes in app.js as below:
// Router configuration
var router = express.Router();
router.route('/user')
.get(userController.getUser)
.post(userController.postUser);
app.use('/api', router);
Is it possible to put Express router routes in another file like routes.js and call from app.js? I tried with app.get in routes.js and it is working. But it is annoying to add /api for prefix in all routes as below.
module.exports = function(app){
app.get('/user', userController.getUser);
};
Or, is there anyway to use namespace in app.get too? Thank you
Why not just do what you're doing, but in your route file?
var express = require('express');
var router = express.Router();
router.route('/user')
.get(userController.getUser)
.post(userController.postUser);
module.exports = function(app) {
app.use('/api', router);
};
Then you'd have in your app.js file
require('./routes.js')(app);
Routers support namespaces too, so you could even do
app.use('/', require('./routes.js'));
And in your routes file (this can be split across files for modularity)
var express = require('express');
var mainRouter = express.Router();
var userRouter = express.Router();
userRouter.route('/user')
.get(userController.getUser)
.post(userController.postUser);
mainRouter.use('/api', userRouter);
module.exports = mainRouter;
You don't need to declare your routes in app.js, in fact, it's better to have each route in its own file, so you can write a routes/my_route.js file as:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Then in app.js:
var express = require("express");
var myRoute = require("./routes/my_route");
var app = express();
app.use("/my-route", myRoute);

Resources