节点JS路由URL冲突

时间:2016-02-25 16:55:38

标签: javascript node.js express routing

此代码的每一部分都单独工作,但当放在一起时,Article部分(第三部分)将不会加载。我对编码很新,所以我希望有人指出我正确的方向。我认为这是因为第一条路线被执行并且它从未到达第二条路线......但我不知道如何解决它。

// Adds "www." to all URLs

app.all('*', function(req, res, next) {
  if (req.headers.host.match(/^www/) == null) {
    res.redirect('http://www.' + req.headers.host + req.url);
  } else {
    next();     
  }
});

// Serves the .html file but displays without .html in the URL

app.get('*', function(req,res){
  var pages = ['/now', '/home', '/itinerary','/exploreourroots','/contact','/credits'];
  if (pages.indexOf(req.url.toLowerCase()) !== -1) {
    res.sendFile(__dirname + '/public' + req.url + '.html');
  };
});

// Loads Articles from the database on the home page

app.get('/home', function(req, res) {
  var query = 'SELECT a.title,a.author,a.cover_photo,a.html_loc,a.date_published,c.name country_name FROM articles a INNER JOIN countries c ON c.id=a.country_id ORDER BY a.date_published desc;'
  connection.query(query, function(err, rows, fields) {
    var list = [];
      for (var i = 0;i < rows.length; i++) {
        list.push({html_loc: rows[i].html_loc,country_name: rows[i].country_name,cover_photo: rows[i].cover_photo,title: rows[i].title,author: toAuthorPhoto(rows[i].author),date_published: toArticleDate(rows[i].date_published)});
      } 
    res.contentType('application/json');
    res.send(list);
  });
});

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

我不确定你有什么意图。

如果用户在浏览器www.mydomain.com/home中输入内容,该怎么办?您想要返回静态html文件(home.html),这是由第二个路由器完成的。或者你想从db(第三条路线)发表文章?

如果你想在url为/home时从db提供文章,那么替换第二和第三条路线的顺序:

app.get('/home', function(req, res) { ... });


app.get('*', function(req,res){ ... });

如果您想要在路由/home时提供静态HTML,并且您希望有可能提供文章,那么就像之前一样替换订单并另外将/home路由器更改为/article 。如果网址为/article,则您将投放文章:

app.get('/article', function(req, res) { ... });


app.get('*', function(req,res){ ... });
相关问题