2017-06-16 71 views
0

我正在使用Express處理Node.js項目。我試圖使用NPM請求包和給定的URL來獲取數據,並傳遞一個匿名回調函數來使用生成的JSON文件。如何將req.params傳遞給node.js中的回調函數

我對下面的代碼沒有任何問題。然而,我嘗試將get-endpoint改爲/ articles /:articleid,以便res.send()取決於瀏覽器發送的req.params.articleid的單獨的不同文章。

這裏是我嘗試過的東西:1.我試圖從回調函數中取出變量newsData ......(我不太確定如何將它拉出來,但我不斷收到一條日誌,說newsData是未定義的。)2.我試圖將req.params.articleid傳遞給回調函數,以便它可以在其中完成它的工作。

你能幫我嗎?謝謝!

app.get('/articles/:articleid', function(req, res) { 
    // I was trying to declare a variable so that I can pull the data out to 
    // the variable... is it plausible? 
    var newsData = {}; 
    var url = "https://newsapi.org/v1/articles?source=techcrunch&apiKey=9667e9e4e1de495ba09b4b875dff8039"; 
    var info = '';   

    // var data = request({ }, function() { return newsData }); It did not return 
    // the newsData to the variable but the request object. Is there any way I can 
    // get the data in this way? 
    request({ 
     url: url, 
     json: true 
    }, function(error, response, body) { 
     if (!error && response.statusCode === 200) { 
      newsData = body; //JSON data 
      newsData.articles.forEach(function(article) { 
       info += ` 
       <article> 
        <h2>${article.title}</h2> 
        <span>Published at ${article.publishedAt}</span> 
        <p>${article.description}</p> 
        <a href="${article.url}"><img src="${article.urlToImage}"></img></a> 
       </article> 
       ` 
      }) 
      res.send(` 
        <h1>Techcrunch</h1> 
        <div class="articles"> 
         <article> 
          <h2>${article.title}</h2> 
          <span>Published at ${article.publishedAt}</span> 
          <p>${article.description}</p> 
          <a href="${article.url}"><img src="${article.urlToImage}"></img></a> 
         </article> 
        </div> 
      `); 
     } 
    }); 
}); 
+0

是舒爾但是,爲什麼?爲什麼不簡單地在回調中做到這一點? –

+0

我很難與req.params.articleid達成回調。我只是不明白如何。當我嘗試時,控制檯一直說它是不確定的。 – Hooey

+0

@ hoey因爲你必須做app.get(「/ articles /:articelId」,...) –

回答

0

解析來自請求回調身上帶JSON.parse(身體),並嘗試它。我有以下工作代碼示例

var app = require('express')(); 
var request = require('request'); 

app.get('/',function 
(req,res){ 
    var url = 'http://www.swapi.co/api/people/1'; 
    request(url,function(error,response,body){ 
    var jsonRes = JSON.parse(body);// This is the response from Endpoint containing the object of results 
    console.log(typeof jsonRes); 
    console.log('error:', error); 
    console.log('statusCode:', response && response.statusCode); 
    console.log(jsonRes.name); 
    res.send(` 
     <strong>Name: </strong> <p> ${jsonRes.name}</p><br> 
     <strong>Height: </strong> <p> ${jsonRes.height}</p> <br> 
     <strong>Mass: </strong> <p> ${jsonRes.mass}</p> 
     `); 
    }) 
}) 

app.listen(4000); 
相關問題