如何将req.params传递给node.js中的回调函数

时间:2017-06-16 05:00:59

标签: javascript node.js express

我正在使用Express处理我的Node.js项目。我试图使用NPM请求包和给定的URL来提取数据,并传递一个匿名回调函数来使用生成的JSON文件。

我对下面的代码没有任何问题。但是,我尝试将get-endpoint更改为/ articles /:articleid,以便根据浏览器发送的req.params.articleid res.send()个别不同的文章。

以下是我尝试过的事情:1。我试图从变量函数中取出变量newsData ...(我不太清楚如何正确地将它拉出来。我不断得到一条日志说newsData是undefined。)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>
           `);
        }
    });
});

1 个答案:

答案 0 :(得分:0)

使用JSON.parse(body)从请求回调中解析主体并尝试它。我有以下工作代码示例

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