I'm building my first app in express. Is it possible to somehow pass a route segment as an argument to a callback?
app.get('/connect/:mySegment', myCallback(mySegment));
Specifically, I'm using passport with several strategies for authentication. So rather than doing,
app.get('/connect/twitter',
passport.authorize('twitter')
);
app.get('/connect/facebook',
passport.authorize('facebook')
);
I would like to do something along the lines of...
app.get('/connect/:service', passport.authorize(service));
Of course, you can do
app.get('/connect/:mySegment', function(req, res){
// then you can use req.params.mySegment
});
Related
I have two routes as follow in my ExpressJs application
router.get("/task/", Controller.retrieveAll);
router.get("/task/seed/", Controller.seed);
If I make a request on /task/seed/ instead of Controller.seed, Controller.retrieveAll is getting called.
So basically router matches the /task/ string before it checks the proceeding string, in my case /seed.
How can I make sure that the router does check the full string (kind of exact match)?
The example you show using router.get() or app.get() does not actually occur. router.get() does not do partial matches unless you're using wildcards or regexes.
I verified that in this simple test app:
const express = require('express');
const app = express();
app.get("/task/", (req, res) => {
res.send("got /task");
});
app.get("/task/seed", (req, res) => {
res.send("got /task/seed");
});
app.listen(80);
When you request /task/seed, you get the message got /task/seed so, it does route correctly.
On the other hand, router.use() does do partial matches so this problem could occur if your actual code was using .use(), not .get(). In that case, you just need to either switch to the verb-specific .get() instead of using the generic .use() or you need to order your routes from the most specific to the least-specific so that the most-specific declaration gets a chance to match first:
router.use("/task/seed/", Controller.seed);
router.use("/task/", Controller.retrieveAll);
In case you're curious, the two main differences between router.use() and router.get() are:
.get() only matches GET requests while .use() matches all HTTP verbs.
.get() only does full path matches while .use() will match any URL path that starts with what you specify.
Execution of express router middleware functions is sequential. There is no keyword like exact, as we have in react-router to make the router check for exact path match.
To make your code work, and always when creating express routes, have the path with the higher specificity above the path with lesser specificity.
So, this should work:
router.get("/task/seed/", Controller.seed);
router.get("/task/", Controller.retrieveAll);
These earlier StackOverflow answers will be very helpful:
https://stackoverflow.com/a/32604002/6772055
https://stackoverflow.com/a/27317835/6772055
Question about express middleware. Say I have a route like the following:
router.route('/replies/:board')
.post(bodyThreadIdVal, textVal, passVal, replyHandler.postReply)
Now let's say I wanted to move the first three middleware arguments from above out of the post method and into a custom method I created in another file, named postReply. How would I go about doing this? I thought maybe using app.use within my postReply method but not sure exactly how or if there is a cleaner way.
I have tried a few methods including
this.postReply = async (req, res, next) => {
app.use(bodyThreadIdVal, textVal, passVal)(req, res, next)
/* additional code */
}
But this seems to cause a recursive loop that rejects with Maximum call stack size exceeded
If the only reason of moving middlewares into a sepparate file is groupping them in one place and making code cleaner and there is no necessity to create a function that will combine your middlewares then I would suggest to group such connected middlewares into an array:
const postReply = [bodyThreadIdVal, textVal, passVal];
router.route('/replies/:board')
.post(...postReply, replyHandler.postReply);
If you will need to add some /* additional code */ just create a new middleware and add it to postReply array. This is definitely much cleaner way.
Currently I have two routes in my app:
/invoice/:invoice returns JSON data of an Invoice document from Mongoose
/invoice/preview returns a preview of an invoice inside an HTML template (note that this doesn't always preview an existing invoice, it could also be a non-existing of which its data is supplied via url parameters, which is why the route cannot be /invoice/:invoice/preview)
Question
There should be a better way to declare these two specific routes, because the /invoice/preview route now calls both handlers, since it matches both regexes.
If we were talking in CSS selectors /invoice/:invoice:not(preview) would be the behavior I want. Unfortunately I don't find any documentation for this.
Is there any way to achieve this or any way to improve this endpoint structure?
Declare more specific routes first:
router.get('/invoice/preview', ...);
router.get('/invoice/:invoice', ...);
Express checks routes in order of declaration, so once it has matched a request against /invoice/preview (and provided that its handler sends back a response), the less-specific /invoice/:invoice won't be considered.
Alternatively, if :invoice should always match a specific pattern (say a MongoDB ObjectId), you can limit the route to requests matching that pattern:
router.get('/invoice/:invoice([a-fA-F0-9]{24})', ...);
That pattern doesn't match "preview", so the order wouldn't matter so much in that case.
If this isn't possible, you could create a middleware that would check if req.params.invoice matches "preview" and, if so, would pass along the request further down the handler chain:
let notIfPreview = (req, res, next) => {
if (req.params.invoice === 'preview') return next('route');
next();
};
router.get('/invoice/:invoice', notIfPreview, ...);
router.get('/invoice/preview', ...);
(documented here)
I'm writing some rest API with Node.JS and Express. So for each API, I'd need to do all the usual stuff like parameter validation, authentication, authorization and then the actual business logic. Some sodo code to illustrate this:
router.get('/users', function (req, res){
async.auto(
authenticateCaller();
authorizeCaller();
validateParams();
doGetUsers();
)
})
This style certainly works but it makes the whole function very cumbersome by including a lot of extra pre-purpose codes. I know in web app programming, MVC has been introduced to separate UI, Module and Controller into different code groups, which is much cleaner. Is there any similar framework that can be helped to achieve this purpose?
Use middleware. Middleware is just a function that takes in three parameters:
function (req, res, next) {}
Call router.use() to register middleware before defining any routes. This will cause that middleware to be called before every route is executed.
These are all functions of middleware:
authenticateCaller();
authorizeCaller();
validateParams();
http://expressjs.com/en/guide/using-middleware.html
This is what I do.
Using Routes for Node.js Here I am making way for a folder named routes that has all the codes in it.
var routes = require('./routes');
var route_add_user = require('./routes/add_user');
Calling the function with the route here; .adduser is function name within that js file
app.get('/adduser', route_add_user.adduser);
define a function do your routine jobs
fuction auth(res,req,next){
authenticateCaller();
req.isAuthorized = authorizeCaller();
validateParams();
next();
}
router.get('/users',auth);
router.get('/users', function (req, res){
if( req.isAuthorized)
{..do some stuff here..}
})
This is one of the STYLE i was following to authenticate and use the API in express framework.
register.js
-----------
exports.addUser = function(req, res) {
// do something
};
exports.deleteUser = function(req, res) {
// do something
};
routes.js
---------
var register = require('./register');
router.get(‘/register’,auth, register.addUser);
router.get(‘/deleteUser’,auth, register.deleteUser);
// Better make it separate common file to reuse all the API
function auth(req,res,next) {
// do something to authenticate your API
}
It seems that if I want to move to a "next" function in Nodejs (and possibly Javascript in general?) I cannot pass parameters to the next function.
Here is what I mean:
app.get('/webpage', SomeFunction, NextFunction);
function SomeFunction (req, res, next) {
// Do things
next();
}
function NextFunction (req, res) {
// Do other things
}
Now, if in SomeFunction I were to say next(req, res); it does not seem to work. It never gets to the method. Obviously I cannot directly pass parameters...but my question is why? How does the next function know which parameters to use? Is it because they are named the same or does it automatically pass the 1st and 2nd parameters? If NextFunction used blah, bleet instead of req, res would it still work?
This is an intentional aspect of the design of Connect (the node.js middleware that's responsible for this behaviour). The next function your middleware receives is not the next middleware in the stack; it's a function that Connect generates which asks the next middleware to handle it (as well as doing some extra stuff to handle special cases, like when there isn't a "next middleware").
If your middleware should return a response, just do so. If it shouldn't, it's implied that some later middleware should return a response. If you need to pass along data to that later part of the process, you should attach it to an appropriate part of the request object req.
For example, the bundled bodyParser middleware is responsible for populating req.rawBody and req.body based on the contents of the request body. The bundled basicAuth middleware populates req.remoteUser based on the HTTP authentication.
This is the pattern you should try to emulate: a stack of middleware, each of which does a basic incremental thing to process the request. If what you're trying to model doesn't fit into this paradigm, then you should probably just have a single function to handle the request, from which you can call all of your own application logic however you like.