[英]How to catch error when parameters is missng using req.params? - Node.js
[英]How to pass req.params to a callback function in node.js
我正在使用Express开发我的Node.js项目。 我尝试使用NPM请求包和给定的URL提取数据,并传递匿名回调函数以利用生成的JSON文件。
我下面的代码没有任何问题。 但是,我尝试将get-endpoint更改为/ articles /:articleid,以便根据浏览器发送的req.params.articleid来res.send()单独撰写不同的文章。
这是我尝试过的事情: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>
`);
}
});
});
使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.