2016-02-25 109 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