如何在快递路由器中获得动态电流路径

时间:2019-03-14 10:15:41

标签: javascript node.js express

router.get('/add/:id', (req, res, next) => {
        let productId = req.params.id;
        let cart = new Cart(req.session.cart ? req.session.cart : {});
        
        cart.addByOne(productId);
        req.session.cart = cart;
        
        // the path name below should be dynamic
        res.redirect('/shopping-cart');
        res.redirect('/checkout');
    });

router.get('/shopping-cart', (req, res, next) => {
    if(!req.session.cart) {
        return res.render('shopping-cart', {products: null});
    }
    let cart = new Cart(req.session.cart);
    res.render('shopping-cart', {products: cart.generateArray(), totalPrice: cart.totalPrice});
});

router.get('/checkout', isLoggedIn, (req, res, next) => {
    if (!req.session.cart) {
      return res.redirect('/shopping-cart');
    }

    let cart = new Cart(req.session.cart);
    res.render('checkout', {products: cart.generateArray(), total: cart.totalPrice});  
});

重定向的路径名应该是动态的,这意味着如果当前的本地路径名是http://localhost:5002/shopping-cart,则应该是res.redirect('/ shopping-cart');

如果本地主机名称为http://localhost:5002/checkout,则应将其更改为res.redirect('/ checkout'),依此类推。有没有办法动态地更改它,并保持该代码尽可能的干净。路由器已定义,文件为checkout.ejs和shopping-cart.ejs。

1 个答案:

答案 0 :(得分:0)

let currentUrl; 

router.get('/add/:id', (req, res, next) => {
    let productId = req.params.id;
    let cart = new Cart(req.session.cart ? req.session.cart : {});

    cart.addByOne(productId);
    req.session.cart = cart;
    res.redirect(currentUrl);
});

router.get('/shopping-cart', (req, res, next) => {
    if(!req.session.cart) {
        return res.render('shopping-cart', {products: null});
    }

    currentUrl = '/shopping-cart';

    let cart = new Cart(req.session.cart);
    res.render('shopping-cart', {products: cart.generateArray(), totalPrice: cart.totalPrice});
    console.log('shopping-cart' + url);
});

router.get('/checkout', isLoggedIn, (req, res, next) => {
    if (!req.session.cart) {
      return res.redirect('/shopping-cart');
    }

    currentUrl = '/checkout';

    let cart = new Cart(req.session.cart);
    res.render('checkout', {products: cart.generateArray(), total: cart.totalPrice});  
});

通过创建一个名为currentUrl的全局变量,我将当前路径名存储在此处,因此,每次路由器加载时,它都会寻找新的更新的currentUrl。