Express JS Router middlewares - javascript

In the code below I want to restrict access to the 'restrictedRoutes' routes without authorization. But in this case 'restrictedRoutes' affects on any routes excluding 'router'.
For example, if I try to access to the '/test', I want to get 404 error, but instead I'm getting JWT-error about invalid token, If that not provided.
How I can create middleware, that will affects only on routes that provided by certain 'Router'?
/*
* API Routes file
*/
var jwt = require('jsonwebtoken');
var router = require('express').Router();
var restrictedRouter = require('express').Router();
module.exports = function (express, app) {
//Default routes
router.get('/login', app.controllers.HomeController.login);
restrictedRouter.use(function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
//Restricted routes
restrictedRouter.get('/', function (req, res) {
res.send('Success');
});
express.use(router);
express.use(restrictedRouter);
};

Mount the router to some path you want to be restricted.
app.use('/restricted', restrictedRouter);
Also I'd avoid the confusion of passing along express and app like you are doing and instead do it like this:
index.js
var express = require('express');
var app = express();
var routes = require('./routes');
app.use('/restricted', routes.restrictedRouter);
app.use(routes.router);
routes.js
var express = require('express');
exports.router = express.Router();
exports.restrictedRouter = express.Router();
router.get('/login', app.controllers.HomeController.login);
restrictedRouter.use(function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
//Restricted routes
restrictedRouter.get('/', function (req, res) {
res.send('Success');
});
Your other option is to use the middleware per route:
var authMiddleware = function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
router.get('/', authMiddleware, function(req, res) {
res.send('Success');
});

Related

Hi all, How can use a variable from one route file to another route file?

personalinfo.js
var express = require("express"),
router = express.Router(),
personalinfo = require("../models/personalinfo");
// To show PersonalInfo
router.get("/new", function(req, res) {
res.render("personalinfo/new");
});
// To create personalInfo date
router.post("/new", function(req, res) {
const personalInfo = req.body.personalinfo;
console.log(personalInfo);
personalinfo.create(req.body.personalinfo, function(err, ninfo) {
if (err) {
res.send(err);
} else {
res.redirect("/objective/new");
}
});
});
module.exports = router;
obj.js
var express = require("express"),
router = express.Router(),
objective = require("../models/objective");
router.get("/new", function(req, res) {
res.render("objective/new");
});
router.post("/new", function(req, res) {
objective.create(req.body.objective, function(err, nobj) {
if (err) {
res.send(err);
} else {
res.send(nobj);
}
});
});
module.exports = router;
From the personalinfo.js route file I want to use the personalInfo variable in obj.js route file. How can I do that. Thanks for helping me. :)
You can use a module in node.
npm install connect-flash
var express = require('express');
var flash = require('connect-flash');
var app = express();
app.use(flash());
app.get('/login', function(req, res){
req.flash('profileInfo', 'SomeText')
});
app.get('/profile', function(req, res){
let message = req.flash('profileInfo')
res.render('index', { message: message });
});
More info about NPM package

Express use function

The below code not functioning as expected
var express = require('express');
var app = express();
app.use(function(req, res, next) {
console.log('first text');
next();
}, function (req, res, next) {
console.log('secondText');
res.end()
}).listen(3000)
app.use([path,] function [, function...])
Mounts the specified middleware function or functions at the specified path. If path is not specified, it defaults to '/' in express documentation but I can't run the second function, not sure why. When I try localhost:3000 in Firefox I receive Cannot GET /
This code is working, but previously it wasn't working:
var express = require('express');
var app = express();
app.use(function(req, res, next) {
console.log("one");
next();
})
.use(function(req,res,next){
console.log("second");
res.end()
})
.listen(3000)
Could it be because of the missing .?
var express = require('express');
var app = express();
app.use(function(req, res, next) {
console.log('first text');
next();
}, function (req, res, next) {
console.log('secondText');
}).listen(3000) //Was missing a period

How to redirect to route from included files

Im having trouble with redirecting to a different route from a required JavaScript file. As you see in oauth2.js i have a function validate which is called when callback from the request.post() method is called. This means I cant pass the express-instantiation (app) as a parameter.
server.js
var app = require('express);
var login = require('./routes/login');
app.use('/login', login);
var oauth2 = require('./oauth2');
oauth2.auth();
app.get('/login', function(req, res) {
res.sendFile('./public/login.html', { root: __dirname });
});
app.listen(8080);
routes/login.js
var express = require('express');
var router = express.Router();
module.exports = function (){
router.get('/login', function(req, res){
console.log('Logging in...');
}
return router;
}
oauth2.js
...
var request = require('request');
request.post({
uri: uri,
headers:headers,
body:data
}, validate);
function validate(err, res, body){
...
// REDIRECT TO /login.html
}
How can I redirect to /login.html from the validate method?
You can use a middleware to grab the response object of express and use it when oauth2 returns a result:
var app = require('express);
var login = require('./routes/login');
app.use('/login', login);
var oauth2 = require('./oauth2');
app.use(function (req, res, next) {
oauth2.auth(function (err, res, body) {
// validate
res.redirect('/login');
});
});
app.get('/login', function(req, res) {
res.sendFile('./public/login.html', { root: __dirname });
});
and your oauth2.js should receive a callback:
// some code..
function auth (cb) {
// some code ..
request.post({
uri: uri,
headers:headers,
body:data
}, cb);
// some code ..
}
// some code ..

how do correctly the routing?

how do correctly the routing
Client:
controller
$scope.exportData = function () {
$http.get('/api/customers/excel/');
};
Server:
controller
var Customer = require('./customer.model');
var excelReport = require('excel-report');
var express = require('express');
var _ = require('lodash');
var fs = require('fs');
// Get list of customers
exports.index = function(req, res) {
Customer.find(function (err, customers) {
if(err) { return handleError(res, err); }
return res.json(200, customers);
});
};
//calling with index
exports.excel = function(req, res) {
console.log('test export');
console.log(__dirname + 'client/template.xlsx');
var template_file ='template.xlsx';
res.download(template_file);
});
};
index (index routes)
var express = require('express');
var controller = require('./customer.controller');
var router = express.Router();
router.get('/', controller.index);
router.get('/excel', controller.excel);
module.exports = router;
routes.
module.exports = function(app) {
// Insert routes below
app.use('/api/customers', require('./api/customer'));
app.use('/api/things', require('./api/thing'));
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
}
i use generator-angular-fullstack for creating project to test
but I have the following error
GET http://localhost:9000/api/customers/excel/ 500
helpme please

Using different router for different subdomains in node.js with express

I want to use different routes in my app, depending on the subdomain in req.headers.host.
So I came around with this idea (extremely simplified example):
var express = require('express');
var domain1 = require('./routes/domain1');
var domain2 = require('./routes/domain2');
var app = express();
app.use('*', domainRouting);
function domainRouting(req, res, next){
var subdomain = req.headers.host.split('.')[0];
if(subdomain === 'domain1'){
app.use(domain1);
}
else{
app.use(domain2);
}
next();
}
//404 handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
res.send('error');
});
var server = app.listen(3001, function() {
console.log('Listening on port %d', server.address().port);
});
domain1.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('DOMAIN 1: ' + req.url);
});
module.exports = router;
domain2.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('DOMAIN 2: ' + req.url);
});
module.exports = router;
But this does not work, the routes are ignored and the request jumps into the last 404-handler.
Any ideas for this?
You can't use app.use() dynamically like that within a middleware. You might call your router directly with domain1(req, res, next) instead of app.use(domain1).
Or you might look into using a module like subdomain to make it easier to handle subdomains in Express.

Categories