【发布时间】:2017-12-14 06:08:38
【问题描述】:
我正在尝试使用 node-fetch 通过 get 调用获取数据。
// Other code
fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
.then(function(data) {
return data.json();
})
.then( function(result){
res.send(result);
});
直到这里数据被成功渲染。我想用函数调用替换这段代码,以便它可以被重用。
我试过了:
function getDataFromUrl(){
fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
.then(function(data) {
return data.json();
}).then( function(result){
return result;
});
}
打电话给getDataFromUrl(),却一无所获。
也试过了:
function getDataFromUrl(){
return fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
.then(function(data) {
return data.json();
}).then( function(result){
console.log(result); // prints desired data
return result;
});
}
并在浏览器中获得{}。
请帮助我(一个节点学习者)从错误中恢复过来。
【问题讨论】:
标签: node.js nodes node-fetch