development

express.js-한 줄의 여러 경로에 대한 단일 라우팅 처리기

big-blog 2020. 9. 2. 20:12
반응형

express.js-한 줄의 여러 경로에 대한 단일 라우팅 처리기


단일 함수 호출에서 이것을 만드는 방법이 있습니까?

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

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

다음과 같은 것 :

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

나는 이것이 구문 엉망이라는 것을 알고 있지만 내가 달성하고 싶은 아이디어를 제공하기 위해 경로 배열이 멋질 것입니다!

누구든지 이것을하는 방법을 알고 있습니까?


동일한 기능을 찾는 동안이 질문을 보았습니다.

@Jonathan Ong는 위의 주석에서 경로에 배열을 사용하는 것은 더 이상 사용되지 않지만 Express 4에서 명시 적으로 설명되어 있으며 Express 3.x에서 작동한다고 언급했습니다. 다음은 시도해 볼 수있는 예입니다.

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

    }
);

request객체 내부에서 경로가 /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"
}, 

매개 변수에서 발생하는 일에 유의하십시오. 현재 요청에서 사용되는지 여부에 관계없이 가능한 모든 경로에서 캡처 그룹 및 매개 변수를 인식합니다.

따라서 배열을 통해 여러 경로를 쌓는 것은 쉽게 수행 할 수 있지만 매개 변수 또는 캡처 그룹을 통해 사용 된 경로에서 유용한 것을 선택하려는 경우 부작용을 예측할 수 없습니다. 중복 / 앨리어싱에 더 유용 할 것입니다.이 경우 매우 잘 작동합니다.

편집 : 아래 @ c24w의 답변도 참조하십시오 .

편집 2 : 이것은 적당히 인기있는 대답입니다. 대부분의 Node.js 라이브러리와 마찬가지로 ExpressJS는 움직일 수있는 축제입니다. 위의 라우팅은 여전히 ​​작동하지만 (지금은 매우 편리한 기능입니다.) 요청 객체의 출력을 보증 할 수 없습니다 (제가 설명한 것과 확실히 다릅니다). 원하는 결과를 얻으려면 신중하게 테스트하십시오.


app.get('/:var(bla|blabla)?', todo)

:var sets the req.param that you don't use. it's only used in this case to set the regex.

(bla|blabla) sets the regex to match, so it matches the strings bla and blablah.

? makes the entire regex optional, so it matches / as well.


You can actually pass in an array of paths, just like you mentioned, and it works great:

var a = ['/', '/blabla', '/blablablabla'];
app.get(a, todo);

Just to elaborate on Kevin's answer, this is from the 4.x docs:

The path for which the middleware function is invoked; can be any of:

  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.

They have some examples, including:

This will match paths starting with /abcd, /xyza, /lmn, and /pqr:

app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) {
  next();
});

I went for a:

['path', 'altPath'].forEach(function(path) {
  app.get(path, function(req, res) { etc. });
});

require the file of your original route and define the new route like this

var user = require('./users');
router.post('/login', user.post('/login'));

참고URL : https://stackoverflow.com/questions/15350025/express-js-single-routing-handler-for-multiple-routes-in-a-single-line

반응형