I have post.route.js where I mention
var post = require('../controllers/post.controller');
router.route('/posts').get(post.getPosts, post.setCache);
and my post.controller.js has the
exports.getPosts = function(req, res, next) {
var qstring = postQueryString;
getPostsDataByQuery(qstring,req,res,next);
}
function getPostsDataByQuery(queryString,req, res, next){
logger.info('start',req.route.path);
// some code here
return res.json(rows);
next();
};
exports.setCache = function(req, res, next){
console.log('here in set function');
cache.setExp(req, rows);
return true;
}
if in the setExp I log the not showing me
exports.setExp = function(req, data){
console.log('here');
}
You could make use of the next method:
function getPosts(queryString, req, res, next){
// your code
next();
};
function setCache(req, res) {
cache.setExp(req.originalUrl, process.env.CACHE_POST_EXP_TIME, rows);
return true;
}
router.route('/posts').get(post.getPosts, post.setCache);
Related
In below example for GET /api/users/i request secondMw is never executed even there is a next() call in firstMw. Why is that? How am I supposed to be able to run the secondMw?
var apiRouter = require('express').Router();
apiRouter.param('user', function firstMw(req, res, next, param) {
if(param === 'i'){
return next(); //jump to next mw sub-stack
}
next('route'); //continue with another matching route
}, function secondMw(req, res, next, param) {
console.log('NO, I AM NOT HERE. NEVER');
next();
});
apiRouter.get('/users/:user', function (req, res, next) {
res.json({
id: req.params.user
});
});
app.use('/api', apiRouter);
I don't see that router.params supports middleware stack (compare definition with app.get). But you can use ordered definition for same route.
'use strict';
let express = require('express');
let app = express();
app.use(require('body-parser').urlencoded({extended: false}));
var apiRouter = express.Router();
apiRouter.param('user', function mw1(req, res, next, param) {
console.log('MW1', param);
if (param === 'i')
next();
else
next('Error message'); // better next( new Error('Error message'));
});
apiRouter.param('user', function mw2(req, res, next, param) {
console.log('MW2', param);
next();
})
// If next() have params then Express calls handler error
apiRouter.use(function (err, req, res, next) {
console.log('Error: ', err)
res.send(err.message || err);
});
apiRouter.get('/users/:user', function (req, res, next) {
res.json({id: req.params.user});
});
app.use('/api', apiRouter);
app.listen(3000, function () {
console.log('Listening on port 3000');
});
I have the following sample middleware component that I want to display in the index.jade file. Is this possible? How do you add the req.requestTime in the Jade template?
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
next();
};
app.use(requestTime);
Add a property to res.locals and you can use it in Pug (formerly Jade)
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
res.locals.requestTime = req.requestTime;
next();
};
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
res.locals.requestTime = req.requestTime;
next();
};
//Jade renderer
var jadeRenderer = function(req, res) {
var jadeFile = 'path/to/jade/template';
var jadeVars = {
locals: req.locals,
queryParams: req.query //if you desire?
};
res.render(jadeFile, jadeVars, function(err, html) {
if(err) {
//handle error
}
res.send(html);
});
};
//jade template
<p>#{locals.requestTime}</p>
Here is the example:
var app = require('express')();
function validateToken(req, res, next) {
// Do something with request here
next();
};
app.get('/user/login', function(req, res) {
//code
});
app.post('/user/register', function(req, res) {
//code
})
app.put('/user/register', validateToken, function(req, res) {
//code
})
app.delete('/user/delete', validateToken, function(req, res) {
//code
})
If I have 10 api that need validToken, I should add validToken middleware 10 times, like:
app.method('......', validateToken, function(req, res) {
//code
})
app.method('......', validateToken, function(req, res) {
//code
})
....
app.method('......', validateToken, function(req, res) {
//code
})
app.method('......', validateToken, function(req, res) {
//code
})
How can I group api by using the same middleware?
Here's how to re-use the same callback function for multiple routes (like middleware):
var app = require('express')();
function validateToken(req, res, next) {
// Do something with request here
next();
};
app.get('/user/login', function(req, res) {
// code
});
app.post('/user/register', function(req, res) {
// code
});
// Be sure to specify the 'next' object when using more than one callback function.
app.put('/user/register', validateToken, function(req, res, next) {
// code
next();
});
app.delete('/user/delete', validateToken, function(req, res, next) {
// code
next();
});
Also, you can replace app.METHOD (e.g. .post, .get, .put, etc.) with app.all and your callback will be executed for any request type.
Just wrong, so do not put into mass participation of the (Google translated from: 刚才看错了,改成这样就不用放进传参了)
var group = {url:true,url:true,url:true};
app.use(function(req,res,next){
if(group[req.url]){
// Do something with request here
next();
} else {
next();
}
})
I have a middleware setup in node to perform a task and call next upon success or failure. The task is called after an initial promise block runs. It is called in the .then function:
var Q = require('q');
var dataPromise = getCustomerId();
dataPromise
.then(function(data) {
getGUID(req, res, next);
}, function(error) {
console.log('Failure...', error);
});
};
The server hangs though because the (req,res,next) parameters are all undefined when in the context of the .then function.
Here is getCustomerId function:
var getCustomerId = function() {
var getCustomerIdOptions = {
options...
};
var deferred = Q.defer();
request(getCustomerIdOptions, function(err,resp,body){
if(err){
deferred.reject(err);
console.log(err);
return;
}else{
deferred.resolve(body);
}
});
return deferred.promise;
};
What would be the correct way to pass these parameters to the function called in the .then block?
EDIT:
The (req,res,next) parameters are from the outer function and are accessible when getGUID(req,res,next) is called outside of the .then() block.
var assureGUID = function(req, res, next) {
if(app.locals.guid){
next();
return;
}
var dataPromise = getCustomerId();
dataPromise
.then(function(data) {
getGUID(req, res, next)
}, function(error) {
console.log('Failure...', error);
}).;
};
Not sure what you are trying to do exactly, but you can call your promise function inside a express common middleware function like the next sample.
var express = require('express');
var $q = require('q');
var request = require('request');
var app = express();
// Middleware 1
app.use( function(req, res, next) {
console.log('i\'m the first middleware');
getCustomerId().then( function(body) {
console.log('response body', body);
return next();
},
function(err) {
console.log('Error on middlware 1: ', err);
});
});
// Middleware 2
app.use( function(req, res, next) {
console.log('i\'m the second middleware');
return next();
});
app.get('/', function(req, res) {
res.send('hi world');
});
app.listen(3000);
// Your custom function definition
function getCustomerId() {
var deferred = $q.defer();
request('http://someurltogetjsondata/user/id', function(err, resp, body) {
if(err) return deferred.reject(err);
deferred.resolve(body);
});
return deferred.promise;
}
I hope this helps a little, good luck.
I am trying to add two authentication controllers to one route. For example, this is basically what I am trying to make:
router.route('/employees')
.get(authController1.isAuthenticated, myController1.get1)
.get(authController2.isAuthenticated, myController2.get2);
The isAuthenticated function is as follows:
exports.isAuthenticated = passport.authenticate('basic', {
session: false
});
Does anyone know how this would be possible?
Thanks,
Daniel
Route:
router.route('/employees')
.get(authController.isAuthenticated1, authController.isAuthenticated2, myController1.get1)
authController :
exports.isAuthenticated = function(req, res, next) {
// Authentication code
if (!req.isAuthenticated) {
// Not authenticated
return res.status(401).send({
message: 'User is not authenticated'
});
}
next();
};
exports.isAuthenticated2 = function(req, res, next) {
// Authentication2 code
if (!req.isAuthenticated2) {
// Not authenticated
return res.status(401).send({
message: 'User is not authenticated'
});
}
next();
};
myController
exports.get1 = function(req, res) {
// Both are authenticated so we can proceed.
}
Perhaps something like this?
exports.isAuthenticated = function(req, res, next) {
req.user == 'type1' ? fnType1(req, res, next) : fnType2(req, res, next); // Do check and call method.
};
function fnType1(req, res, next) {
//Authentication code
// Attach type to req
req.userType = 1;
next();
}
function fnType2(req, res, next) {
//Authentication code
// Attach type to req
req.userType = 2;
next();
}
exports.get1 = function(req, res) {
// Both are authenticated so we can proceed.
if(req.userType = 1){
// Do something
} else {
// Do something else
}
}