2016-02-25 91 views
3

这段代码中的每一段都单独工作,但放在一起时,文章部分(第三集)将不会加载。我对编码相当陌生,所以我希望有人能指出我正确的方向。我认为这是因为第一条路线被执行了,它从来没有碰到第二条路线......但我不知道如何解决它。节点JS路由URL冲突

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

感谢您的帮助!

+0

说明。只有/ home工作不正常,因为它也在*中使用。 – TreeOfNations

回答

2

我不确定你有什么意图。

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

如果你想从数据库服务的文章时,网址为/home,然后更换第二和第三路线的顺序:

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


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

,如果你想为静态html当你的路线/home,你也想有可能发送物品,然后像以前一样更换订单,并另外将/home路由器更改为/article。然后,如果网址为/article,那么您将投放文章:

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


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

欣赏回应!我实际上昨天修好了它,结果和你概括的一样......效果很好。 – TreeOfNations