2016-05-03 5 views
0

ノード/エクスプレッション側で、作成したばかりのエンドポイントにリクエストを送信しようとしています。APIエンドポイントの所有者に依頼する

これを行う正しい方法は何ですか?私は「別のrouter.get(..)外部API

+2

試してみてください。 – Andy

+0

私の試みによってページがハングアップする – darkace

+1

'/ weather'とは何ですか?それはAPIを持つ別のサイトですか、それとも自分のサーバーですか?サーバー/クライアントコードが混在しているようです。 – Andy

答えて

1

を使用して気象データを取得する方法がある

router.get('/displayweather', function(req, res) { 

    fetch('/weather') 
    .then(function(response){ 
     res.send(response); 
    }); 
}); 

router.get('/weather', function(req, res){ 
    var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json'; 
    fetch(fetchUrl) 
    .then(function(response){ 
     if (response.status >= 400) { 
     throw new Error("Bad request response from server"); 
     } 
     return response.text(); 

    }).then(function(body) { 
     res.send(body); 

    }); 

}); 

:私はフェッチライブラリ(同型フェッチ)

マイ試みを使用することができますその最初の部分を忘れて、あなたが追加したコードに集中dは:

サーバー

router.get('/weather', function(req, res){ 
    var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json'; 
    fetch(fetchUrl) 
    .then(function(response){ 
     if (response.status >= 400) { 
     throw new Error("Bad request response from server"); 
     } 

     // return json 
     return response.json(); 
    }).then(function(body) { 

     // but stringify it when you send it 
     res.send(JSON.stringify(body)); 
    }); 
}); 

クライアント

+0

これは意味があるので、バックエンドでこれを行うことはできません。それとも悪い習慣であり、機能を複製するためにモジュールを使用する必要がありますか? また、レスポンスオブジェクトの扱い方がわからないため、あなたが仕事に与えた例は得られません。 – darkace

関連する問題