I'm trying to add an argument to a function passed along as an argument in an express js route.
This is an expressjs route:
app.get('path', someFunc,
function(req, res, next) {
res.render('layout');
});
The function someFunc right there takes the arguments req, res, next.
I want to add an additional argument to it. If I use apply or call it seems to replace all the existing arguments.
I want to be able to do:
someFunction (req, res, next, custom) {}
How can I do this? Thanks.
I am not sure that this is the best way but you could do something like this :
var someFunc = function (req, res, next, custom) { console.log(custom); next(); }
app.get('path',
function (req, res, next) { someFunc(req, res, next, 'custom') },
function(req, res, next) {
res.render('layout');
});
I would create a route like this:
// Inside your routes.js:
module.exports.someRoute = function(myArgument) {
return function(req, res, next) {
// Do whatever you want with myArgument.
};
};
// Inside your app.js:
app.get('path', routes.someRoute({ foo: 1 }));
This way your route setup is clear of any logic.
Related
IS there any way i can dynamic take the platform info and process them,even when i tried accessing the value outside the function it is not working since it is a single route file
router.get(
"/:platform",
function data(req, res, next) {
var platform = req.params.platform;
next();
},
passport.authenticate("google", { scope: ["email"] })
);
You can save the data in req and then run the middleware manually
This should work, but I didn't test it
router.get(
"/:platform",
function data(req, res, next) {
req.platform = req.params.platform;
next();
},
(req, res, next) => passport.authenticate(req.platform, { scope: ["email"] })(req, res, next)
);
app.js
// Calling Routes
require("./routes")(app);
router folder
index.js
module.exports = function (app) {
app.use("/", require("./all_routes"));
}
all_routes.js
var express = require("express");
var router = express.Router();
router.get("/", function (req, res, next) {
res.render("home/index.html");
});
//About Page
router.get("/about", function (req, res, next) {
res.render("about/index.html");
});
//Contact
router.get("/contact", function (req, res, next) {
res.render("contact/index.html");
});
//product
router.get("/product", function (req, res, next) {
res.render("product/index.html");
});
//product list
router.get("/product/demo-product", function (req, res, next) {
res.render("demo-product/index.html");
});
router.get("/product/request-product", function (req, res, next) {
res.render("request-product/index.html");
});
//service
router.get("/service", function (req, res, next) {
res.render("product/index.html");
});
//service list
router.get("/service/what-we-do", function (req, res, next) {
res.render("what-we-do/index.html");
});
router.get("/service/how-we-do", function (req, res, next) {
res.render("how-we-do/index.html");
});
I am trying to reduce the code in all_routes.js file has same code is repeating again and again
I searched online and trying to create it dynamically but getting no success is there any way I can reduce the line of code as I have given the follow of my code above
If you'd like to cut down on boilerplate of all your get routes, one option is to create an object to map your routes to the files they're loading. Then you can iterate over that object and add the routes to your router.
const routes = {
"/": "home/index.html",
"/about": "about/index.html",
"/contact": "contact/index.html"
// Add others here
}
for (let key in routes) {
router.get(key, function (req, res, next) {
res.render(routes[key]);
});
}
Edit: If your routes are consistent in that the index.html file will always be in the directory named after the part after the last / in your route, you can potentially use an array and some fancy logic. Just don't break the rule!
const routes = [
"/contact",
"/product",
"/product/demo-product",
"/product/request-product"
]
routes.forEach(route => {
const path = /[^/]*$/.exec(route)[0];
router.get(route, function (req, res, next) {
res.render(`${path}/index.html`);
});
})
How can I insert isLoggedIn as a condition to the get request using router.route?
const controller = require('./controller');
const Router = require('express').Router;
const router = new Router();
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
router.route('/')
.get((...args) => controller.find(...args))
I assume that the ...args are (req, res, next)
I tried
router.route('/')
.get(isLoggedIn(...args) => controller.find(...args))
But I get
.get((isLoggedIn(...args)) => controller.find(...args))
^
SyntaxError: Unexpected token (
The docs say, that you can assign multiple handlers to one route. Like this:
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()
})
Source
In your case the coding looks like the following
router.get('/', isLoggedIn, controller.find);
Hi I am trying to follow ES6 syntax to create a middleware of my node.js application.
index.js
export default class Middleware {
constructor() {
//do nothing
}
fun1 = (req, res, next) => {
console.log("------------------------------------");
console.log("AAa");
console.log("------------------------------------");
next();
};
fun2 = (req, res, next) => {
console.log("------------------------------------");
console.log("AAa");
console.log("------------------------------------");
next();
};
}
app.js
import Middleware from ".index";
app.use(Middleware);
I am getting an error Cannot call a class as a function. Does anyone know what is wrong?
Express app#use expects a function with the following signature:
function(req, res, next) {
To make it work, you need to do:
Create an instance of Middleware class.
Register middleware for each function in the class.
Example:
let middleware = new Middleware();
app.use(middleware.func1);
app.use(middleware.func2);
How can I pass for example the database reference
nano = require('nano')('http://127.0.0.1:5984')
db = nano.use('database')
to a resource 'User' (loaded with express-resource)?
I tried:
app.resource('user', require('./routes/user'), {db: db});
But that doesn't work.
You want to pass db to the user.js routing file. What you are doing is passing it to the app.resource function.
app.resource('user', require('./routes/user')(db));
You will have to wrap your user.js file in a function that can receive db as a parameter.
module.exports = function(db) {
return {
index: function(req, res) {}
, new: function(req, res) {}
, create: function(req, res) {}
// etc
};
};
If you don't like the way this is structured, you can also use a middleware.
app.use(function(req, res, next) {
req.db = db;
next();
});