简体   繁体   中英

How to redirect to a top route from a nested route with node express?

How can I redirect to a top route from a nested route?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM