节点 JS 路由 URL 冲突

Node JS Routing URL Conflict

本文关键字:冲突 URL 路由 JS 节点      更新时间:2023-09-26

这段代码的每一段都单独工作,但放在一起时,文章部分(第三组)将不会加载。 我对编码相当陌生,所以我希望有人能为我指出正确的方向。 我认为这是因为执行了第一条路由,并且它永远不会命中第二条路由......但我不知道如何解决它。

// 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);
  });
});

感谢您的帮助!

我不确定你有什么意图。

如果用户在浏览器中键入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 .然后,如果 url /article,您将提供文章:

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

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