Skip to content

How to rewrite url when using routers #3800

Description

@barisusakli

Hello, trying to rewrite the url to redirect requests but having some problems when the url doesn't have a trailing slash. Here is a minimal app to demonstrate.

const express = require('express')
const app = express()
const port = 3000
const router = express.Router()

const subFolder = '/forum'

app.use(subFolder, rewrite);

function rewrite(req, res, next) {
    console.log(req.path)
    if (req.path !== '/') {
        return next()
    }
    req.url = '/categories'
    app.handle(req, res, next);
}

router.get('/regular-page', (req, res) => res.send('Hello World!'))
router.get('/categories', (req, res) => res.send('Categories'));
app.use(subFolder, router);

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

The goal is to redirect localhost:3000/forum and localhost:3000/forum/ to localhost:3000:/forum/categories. Right now only localhost:3000/forum/ works. The other just 404s.

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions