如何阻止express匹配多条路线?

问题描述 投票:0回答:1

我有一个路由器文件,它以这种方式导入路由,并在

index.js
中需要
require('./router.js')(app)

const index = require('./backend/pages/index')
const somepage = require('./backend/pages/somepage')

module.exports = function (app) {
    app.use('/', index)
    app.use('/:somepage/:page(page/\\d+)?', somepage)
}

在第一个匹配后,路线匹配不会停止,这是我想避免的,与this类似的问题,但那里没有提供解决方案

这是一个路线文件以获取更多信息

const express = require('express'),
    router = express.Router()

router.get('/', async (req, res) => {
    console.log(`test ${Math.random()}`)
})

module.exports = router

我尝试以各种方式重新排列路由器/路线,但这似乎没有帮助,我还尝试将

app.use
更改为 app.get` 但第二条路线没有被拾取

javascript node.js express routes backend
1个回答
0
投票

在 Express 中,定义路由的顺序很重要,第一个匹配的路由将被执行。但是,如果您有一个带有参数的路由(在您的情况下是:somepage),它可以匹配多个路径。 为了确保路由匹配在第一个路由匹配后停止而不考虑后续路由,您可以在路由处理中间件中使用 next('route') 函数。尝试这样的事情,

const express = require('express')
const router = express.Router()

router.get('/', async (req, res, next) => {
    console.log(`test ${Math.random()}`)
    // use next('route') to skip to the next route in the stack
    next('route')
})

// define another route using the same route path
router.get('/', async (req, res) => {
    console.log('This will not be executed if the first route matches')
})

module.exports = router
© www.soinside.com 2019 - 2024. All rights reserved.