2017-07-10 14 views
0

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

を、ブラウザで{}を得た:

も試してみました。

間違いを乗り越えるために(ノード学習者)お手伝いしてください。

答えて

1

この方法であなたの関数を定義します。このように

function getDataFromUrl(resp){ 
    fetch('https://jsonplaceholder.typicode.com/posts?userId=1') 
    .then(function(data) { 
     return data.json(); 
    }).then(function(parsed){ 
     resp(parsed); 
    }); 
} 

、コールを:

getDataFromUrl(function(resp){ 
    res.send(resp); 
}); 
関連する問題