Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

node.js - express.js - single routing handler for multiple routes in a single line

Is there a way to make this on a single function call?

var todo = function (req, res){};

app.get("/", todo);
app.get("/blabla", todo);
app.get("/blablablabla", todo);

Something like:

app.get("/", "/blabla", "/blablablabla", todo );

I know this is a syntax mess, but just for giving an idea of what I would like to achieve, an array of the routes would be awesome!

Anyone know how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I came across this question while looking for the same functionality.

@Jonathan Ong mentioned in a comment above that using arrays for paths is deprecated but it is explicitly described in Express 4, and it works in Express 3.x. Here's an example of something to try:

app.get(
    ['/test', '/alternative', '/barcus*', '/farcus/:farcus/', '/hoop(|la|lapoo|lul)/poo'],
    function ( request, response ) {

    }
);

From inside the request object, with a path of /hooplul/poo?bandle=froo&bandle=pee&bof=blarg:

"route": {
    "keys": [
        {
            "optional": false, 
            "name": "farcus"
        }
    ], 
    "callbacks": [
        null
    ], 
    "params": [
        null, 
        null, 
        "lul"
    ], 
    "regexp": {}, 
    "path": [
        "/test", 
        "/alternative", 
        "/barcus*", 
        "/farcus/:farcus/", 
        "/hoop(|la|lapoo|lul)/poo"
    ], 
    "method": "get"
}, 

Note what happens with params: It is aware of the capture groups and params in all of the possible paths, whether or not they are used in the current request.

So stacking multiple paths via an array can be done easily, but the side-effects are possibly unpredictable if you're hoping to pick up anything useful from the path that was used by way of params or capture groups. It's probably more useful for redundancy/aliasing, in which case it'll work very well.

Edit: Please also see @c24w's answer below.

Edit 2: This is a moderately popular answer. Please keep in mind that ExpressJS, as with most Node.js libraries, is a moveable feast. While the routing above does still work (I'm using it at the moment, a very handy feature), I cannot vouch for the output of the request object (it's certainly different from what I've described). Please test carefully to ensure you get the desired results.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...