Reputation: 10463
I have this module.exports
module.exports = {
defaultStrings: function() {
return "Hello World" +
"Foo - Bar";
},
urlSlug: function(s) {
return s.toLowerCase().replace(/[^\w\s]+/g,'').replace(/\s+/g,'-');
}
};
I want to be able to use request
or response
inside function defaultStrings
how would I include that with a minimum change of the given code?
defaultStrings: function(req, res, next) { // <--- This is not working it says Cannot call method 'someGlobalFunction' of undefined
return "Hello World" +
"Foo - Bar" + req.someGlobalFunction();
},
In my app.js
I require the file in
strings = require('./lib/strings'),
And this is how it is being called inside app.js
app.get('/',
middleware.setSomeOperation,
routes.index(strings);
Upvotes: 0
Views: 266
Reputation: 893
When are you calling defaultStrings
? If you are calling it directly from your routes
i.e. by using app.get("some_url", defaultStrings)
, then req
and res
should be available to you.
EDIT: It appears that you were calling it by: content = strings.defaultStrings();
inside of your index
function. In order to pass on the req
and res
arguments you must simply change your call to content = strings.defaultStrings(req,res,cb)
, where cb
is the callback defined by index
.
Upvotes: 2
Reputation: 636
I'm assuming you're using node.js with express.
If you want access to the http request and response you've got a few options:
Add function myMiddleware as a middleware for all routes
var myMiddleware = function(req, res, next) {
console.log(req.route); // Just print the request route
next(); // Needed to invoke the next handler in the chain
}
app.use(myMiddleware); //This will add myMiddleware to the chain of middlewares
Add function myMiddleware as a middleware for a specific route
var myMiddleware = function(req, res, next) {
console.log(req.route); // Just print the request route
next(); // Needed to invoke the next handler in the chain
}
app.get('/', myMiddleware, function(...) {}); //This will add myMiddleware to '/'
Add function myHandler as a route handler
var myHandler = function(req, res) {
console.log(req.route); // Just print the request route
send(200); // As the last step of the chain, send a response
}
app.get('/', myHandler); //This will bind myHandler to '/'
Upvotes: 0