Node JS: How to open one route within another

问题内容:

I’m newbie in web front-end world. I have routes: /product, /shop. And for each route I have created controllers. The question is how can I open /shop route page from /product page. When I call res.render('product'); it routes http://localhost:3000/shop/products instead of http://localhost:3000/products.

How can i solve this?

问题评论:

    
P.S.: opening /product from /shop
– Bakhrom Achilov
3 hours ago
    
You can edit your question instead of the comment
    
What happens if you call res.render('/product')
    
Nothing, but request is coming to the controller.
– Bakhrom Achilov
3 hours ago

答案:

答案1:

Use

redirect

in your route Express redirect

Example:

app.get('/shop', function(req, res) {
 res.redirect('/products');
});

答案评论:

答案2:

You are redirected to http://localhost:3000/shop/products because the current path before executing the request is: http://localhost:3000/shop
To go on /products directly, you can do the following

  • You can use the .. to invoke the parent in your filesystem (using a relative path)
res.render('../products')
  • Or simply using an absolute path
res.render('/products')

答案评论:

    
I tried, but it crashes
– Bakhrom Achilov
3 hours ago
    
router.get('/', function (req, res, next) { console.log("test"); res.render("../shop"); });
– Bakhrom Achilov
3 hours ago
    
What is the error,please
    
With redirect: It writes “Not Found”, <br />With render: Failed to lookup view “shop-product-render” in views directory “/Users/developer/Desktop/dilenta/views” GET /product 500 3.356 ms – 1352
– Bakhrom Achilov
2 hours ago
    
Are you sure, you have a file associated to the page localhost:3000/products ?

原文地址:

https://stackoverflow.com/questions/47753786/node-js-how-to-open-one-route-within-another

添加评论

友情链接:蝴蝶教程