2017-03-17 84 views
1

所以,我設置了這條路線,它從內部API獲取JSON數據並顯示它。第一次訪問路由時,我得到正確的JSON數據,但是當我刷新頁面時我得到一個錯誤,頁面只是加載。任何想法?
注:我用的請求承諾無法兩次提出請求

app.get('/',function(req,res){ 
var options = { 
//Here I initiate the API call.I actually have a url here. 
uri: '', 
json: true 
}; 

request(options) 
    .then(function(data) { 
     res.json(data); 
     res.end(); 
    }) 
    .catch(function (err) { 
     console.log(err); 
    }); 
}); 
+0

*「當我刷新頁面時出現錯誤」* - 這是...? –

+0

HPE_INVALID_CONSTANT.I刪除緩存,現在它的工作原理,但我不知道如何緩存related.I緩存來自API的響應。 – sterg

回答

0

,因爲你是調用API給了一個錯誤響應你得到控制檯錯誤和頁面加載卡住,但你是不是發在catch回調東西。嘗試這個。

app.get('/',function(req,res){ 
    var options = { 
     //Here I initiate the API call.I actually have a url here. 
     uri: '', 
     json: true 
    }; 

    request(options) 
     .then(function(data) { 
      res.json(data); 
      res.end(); 
     }) 
     .catch(function (err) { 
      console.log(err); 
      res.status(500).send(err); // set proper error code and send response here 
     }); 
    }); 
+0

只是一個快速的我可能在這裏錯了,但在'then'塊'我們不應該做一個res.send(數據)作爲任意res.end?我知道oyu沒有把這個想法放在考慮之中,沒有res.send()方法被激發,響應永遠不會成功:p – Jackthomson

+0

res.send()爲你調用res.end()。 –

+1

@Jackthomson請閱讀['res.json'](https://expressjs.com/en/4x/api.html#res.json)上的文檔。它爲json內容提供'res.send()'的角色。 –