如何使用node express从嵌套路由重定向到顶部路由?

 收藏

如何从嵌套路由重定向到顶部路由?

On the code below, the callback for the route /toproute/nested should redirect to /profile instead of /toproute/profile.

// app.js
const express = require('express');
const app = express();
const topRoutes = require('./top-routes');

app.use('/toproute', topRoutes);

app.use('/about', (req, res) => {
    res.send('About');
});

app.listen(4200, () => {});
// top-routes.js - /toproute

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

router.use('/nested', (req, res) => {
  res.redirect('/profile'); // Should redirect to /profile instead of /toproute/profile
}););
回复
  • As express document, you can pass a relative path to redirect.

    In your case, you can use res.redirect('../profile'); instead of res.redirect('/profile');