nodejs express url rewrite?

穿精又带淫゛_ 提交于 2021-02-11 06:55:54

问题


I am new to nodejs and just started learning it. I started with express. Everything's good but have a question not sure if this needs to be URL rewrite or URL redirect. views folder looks like below, (jade files)

views
  - index
  - news
  - videos

The first page definitely is index, url is localhost:3000. Now I want my news page to be the index page, so when I enter localhost:3000 or localhost:3000/news, I want always to see the news.jade content. but I don't want to duplicate news.jade to index.jade. So I think the best thing is to have a urlwrite, then either localhost:3000 or localhost:3000/news will get news.jade content. if a url rewirte needed to achieve my goal, is below code is a good example?

app.use('/news', function(req, res, next){
    var old_url = req.url;
    req.url = '/index';
    next();
});

I searched a while, but didn't really get an answer, could someone please help? Thanks


回答1:


If you have scaffolded using express-generator, then it would create a routes folder that handles all the routing code. Refer this link to know more on express generator.

You have to edit the index.js file in that folder

   router.get('/', function(req, res, next) {
     res.render('news');
   });

When ever the application receives a / request that is localhost:3000/ it will render the news file.

If you have any more doubt you can refer the manual here http://expressjs.com/en/guide/routing.html

Edit - Fix typo



来源:https://stackoverflow.com/questions/36098136/nodejs-express-url-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!