I have a route router.get('/generateDoc', handleRequest); and I want to run this handleRequest twice. Can someone suggest me how to tackle this situation.
Below is my code example.
function handleRequest(req, res, next) {
for (var i = 0; i < 2; i++) {
cacheService.clean();
PdfController.generatePDfs(req, res, next);
}
}
It's an odd thing to require, but you can do it:
function handleRequestInnards(req, res, next) {
cacheService.clean();
PdfController.generatePDfs(req, res, next);
}
function handleRequest(req, res, next) {
handleRequestInnards(req, res, function() {
handleRequestInnards(req, res, next);
});
}
You would have more luck with a library like Bluebird where you can make this a promise and do stuff like:
function handleRequest(req, res, next) {
Promise.all([
handleRequest(req, res),
handleRequest(req, res)
]).asCallback(next);
}
I think you can also just add the middleware twice:
router.get('/generateDoc', handleRequest, handleRequest);
Related
I had originally been using bodyParser as so:
app.use(bodyParser.json());
However, now I want to conditionally use bodyParser:
app.use((req, res, next) => {
if (req.originalUrl === '/hooks') {
next();
} else {
bodyParser.json()(req, res, next);
}
});
When I try to remove (req, res, next), the parser does not work. That is,
app.use((req, res, next) => {
if (req.originalUrl === '/hooks') {
next();
} else {
bodyParser.json();
}
});
does not work.
Why do I need (req, res, next) after bodyParser.json()?
https://github.com/expressjs/body-parser/blob/master/index.js#L108
function bodyParser (options) {
var opts = {}
// exclude type option
if (options) {
for (var prop in options) {
if (prop !== 'type') {
opts[prop] = options[prop]
}
}
}
var _urlencoded = exports.urlencoded(opts)
var _json = exports.json(opts)
return function bodyParser (req, res, next) {
_json(req, res, function (err) {
if (err) return next(err)
_urlencoded(req, res, next)
})
}
}
Body parser is a middleware that needs access to res, req and next.
It parses your request using req and in order to pass control to the next middleware, it needs access to the next function.
Here app.use(bodyParser.json()); are passed (req, res, next) by default as
bodyParser.json() returns return function bodyParser (req, res, next) { .. }
so it becomes --> app.use(function bodyParser (req, res, next) { .. });
but in your case, you are creating a middleware by your self and you are responsible to pass the parameters to bodyParser so it can have access to the required arguments.
app.use((req, res, next) => {
if (req.originalUrl === '/hooks') {
next();
} else {
bodyParser.json()(req, res, next);
}
});
See how app.use works below
https://github.com/expressjs/express/blob/master/lib/application.js#L187-L242
I am trying to pass some predefined functions in the callback of app.post() method. I am getting next is not defined error. Below is my code. Please suggest where I am doing wrong or am I missing any concept here?
var express = require('express');
var app = express()
app.post('/api/signup', function(req, res) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
where I have each function defined and imported and returning next() after my process.
my validateParams function is below :
validateParams = function(req, res, next) {
console.log("at validator ", req);
next();
}
module.exports = validateParams;
my dbCall function is below :
dbCall = function(req, res, next) {
console.log("at dbCall ", req);
next();
}
module.exports = dbCall;
my sendResponse function is below :
sendResponse = function(req, res) {
console.log("at dbCall ", res);
res.send("Response sent successfully");
}
module.exports = sendResponse;
You probably forgot to add the next argument in your callback.
app.post('/api/signup', function(req, res, next) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
I think you are trying to use validateParams(req, res, next) and dbCall(req, res, next) as middleware functions. In this case, you need something like this:
const validateParams = (req, res, next) => {
// do stuff here
next();
}
const dbCall = (req, res, next) => {
// do stuff here
next();
}
app.post('/api/signup', validateParams, dbCall, function(req, res) {
sendResponse(req, res)
})
You can read more here
I am having a problem with my Node.js app. In short I want to pass custom parameters into my middleware function other than just req, res, and next.
Middleware file:
var DB = require('./DB.js');
function requirePermissions(e) {
console.log('nope')
}
module.exports = requirePermissions;
Route:
router.post('/posts', requirePermissions('post_creation'), function(req, res) {
var o = req.body,
title = o.post.title,
content = o.post.content;
res.send('made it');
});
I have confirmed that using function requirePermissions(req, res, next) {} will work, but I do not understand how to include my own parameters.
Your function requirePermissions should return another function which will be the actual middleware:
function requirePermissions(e) {
if (e === 'post_creation') {
return function(req, res, next) {
// the actual middleware
}
} else if (e === 'something_else') {
return function(req, res, next) {
// do something else
}
}
}
You can also do it like that:
function requirePermissions(e) {
return function(req, res, next) {
if ('session' in req) {
if (e === 'post_creation') {
// do something
} else if (e === 'something_else') {
// do something else
}
}
}
}
You can just create an anonymous function for your middleware that lets you call your actual function with some additional arguments:
router.post('/posts', function(req, res, next) {
requirePermissions('post_creation', req, res, next);
}, function(req, res) {
var o = req.body,
title = o.post.title,
content = o.post.content;
res.send('made it');
});
Or, you can use .bind() to preprend arguments:
router.post('/posts', requirePermissions.bind('post_creation'), function(req, res) {
var o = req.body,
title = o.post.title,
content = o.post.content;
res.send('made it');
});
This will call your requirePermissions() functions with four arguments like this:
requirePermissions('post_creation', req, res, next)
I'm starting with sails js and node more generally .
I'm trying to use the regular way of implementing services in sails to pass data in my controller.
for example, I've a dashboard view, called dashboard.ejs
my view is correctly routed and everything.
But the regular ways of passing data from service wasn't working at all, and I ended up with that to make it work, which seems to be very unappropriate:
my CountService.js:
module.exports = {
RoomCount: function(req, res, cb, tab)
{
Room.count().exec(function(err, roomfound){
tab.push(roomfound);
cb(req, res, tab);
});
},
VenteCount: function(req, res, cb, tab)
{
Vente.count().exec(function(err, ventefound){
tab.push(ventefound);
cb(req, res, tab);
});
},
LotCount: function(req, res, cb, tab)
{
Lot.count().exec(function(err, lotfound){
tab.push(lotfound);
cb(req, res, tab);
});
}
};
My DashboardController.js
module.exports = {
dashboard: function(req, res, next)
{
var tab = []
var end_dashboard = function(req, res, tab){
res.view('dashboard', {
roomCount: tab[0],
venteCount: tab[1],
lotCount: tab[2]
});
};
var callbacklot = function(req, res, tab){
end_dashboard(req, res, tab);
};
var callbackvente = function(req, res, tab){
CountService.LotCount(req, res, callbacklot, tab);
};
var callbackroom = function(req, res, tab){
CountService.VenteCount(req, res, callbackvente, tab);
};
CountService.RoomCount(req, res, callbackroom, tab);
},
};
And then I can call the VenteCount etc values in my view ejs
The regular way was giving a value = undefined
I think I was wrong in the res() or next() part so I ended like that but it makes the service thing very complicated...
Thanks a lot for your help
I have the following code from https://github.com/chjj/tty.js/:
this.get("/hola", function(res) {
iniciar();
});
function iniciar() {
self.init();
}
iniciar();
going to localhost:8080/hola, it does not load. localhost:8080 works perfectly. self.init() calls a function that, in turn, calls other functions. The problem seems to be the following called function:
Server.prototype.initMiddleware = function() {
var self = this
, conf = this.conf;
this.use(function(req, res, next) {
var setHeader = res.setHeader;
res.setHeader = function(name) {
switch (name) {
case 'Cache-Control':
case 'Last-Modified':
case 'ETag':
return;
}
return setHeader.apply(res, arguments);
};
next();
});
this.use(function(req, res, next) {
return self._auth(req, res, next);
});
this.use(term.middleware());
this.use(this.app.router);
this.use(express.static(__dirname + '/../static'));
};
According to express.js documentation:
// a middleware sub-stack which prints request info for any type of HTTP request to /user/:id
app.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
So, it seems that there are "conflicts" between first app.get and the others app.use or this.use. How can I solve that?
it's because you are not returnig anything and then the browser is polling this until it return something.
this.app.get("/hola", function(req, res) {
res.writeHead(200, {'content-type':'text/html'});
res.end('/*html code here*/');
});