2017-04-13 78 views
0

我一直在試圖做兩個鏈接的HTTP請求調用,第二個調用是基於第一個調用的返回結果。要求是第一次打電話獲取IP信息並使用IP信息進行第二次呼叫以獲取天氣數據。我正在使用節點模塊koa-http-requestChaning與Koa.js的兩個HTTP請求

它只適用於一個請求,要麼我只能得到IP或我只能得到天氣數據。

var koa = require('koa'); 
    var koaRequest = require('koa-http-request'); 
    var app = new koa(); 

    var lat = ''; 
    var log = ''; 

    // app.use(koaRequest({ 
    // dataType: 'json', //automatically parsing of JSON response 
    // timeout: 3000, //3s timeout 
    // host: 'http://ip-api.com' 
    // })); 
    // 
    // app.use(async (ctx, next) => { 
    //  var ipObject = await ctx.get('/json', null, { 
    //   'User-Agent': 'koa-http-request' 
    //  }); 
    //  lat = parseInt(ipObject.lat); 
    //  lon = parseInt(ipObject.lon); 
    // }); 

    app.use(koaRequest({ 
     dataType: 'json', //automatically parsing of JSON response 
     timeout: 3000, //3s timeout 
     host: 'http://api.openweathermap.org/' 
    }), next); 

    app.use(async (ctx, next) => { 
     var weatherObject = await ctx.get('/data/2.5/weather?lat=43&lon=-79&appid=***', null, { 
      'User-Agent': 'koa-http-request' 
     }); 
     console.log(ctx.request); 
     ctx.body = weatherObject; 
    }); 

    app.listen(process.env.PORT || 8090); 

回答

0
var koa = require('koa'); 
var koaRequest = require('koa-http-request'); 
var app = new koa(); 

app.use(koaRequest({ 
dataType: 'json', //automatically parsing of JSON response 
})); 

app.use(async ctx => { 
let geoLocation = await ctx.get("https://ipinfo.io/"); 
let loc = geoLocation.loc.split(","); 
ctx.lat = loc[0]; 
ctx.lon = loc[1]; 
const APIKEY = "**"; 
let weather = await 
ctx.get('http://api.openweathermap.org/data/2.5/weather?lat=' + 
ctx.lat + '&lon=' + ctx.lon + '&APPID=' + APIKEY); 

ctx.body = weather; 
}); 

app.listen(process.env.PORT || 8090); 
0

我想最好的辦法是使雙方的要求是這樣的:

'use strict'; 
const koa = require('koa'); 
const koaRequest = require('koa-http-request'); 
const app = new koa(); 

app.use(koaRequest({ 
    dataType: 'json', 
    timeout: 3000 //3s timeout 
})); 

app.use(async (ctx, next) => { 
    let lat; 
    let lon; 

    let ipObject = await ctx.get('http://ip-api.com/json', null, { 
     'User-Agent': 'koa-http-request' 
    }); 
    lat = ipObject.lat; 
    lon = ipObject.lon; 

    let weatherObject = await ctx.get('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid=+++YOUR+APP+ID+++', null, { 
     'User-Agent': 'koa-http-request' 
    }); 
    console.log(ctx.request); 
    ctx.body = weatherObject; 
}); 

app.listen(process.env.PORT || 8090); 

還有一個提示:編輯您的堆棧溢出的問題,並刪除您appid從源代碼。否則,每個人都可以在自己的代碼中使用您的Aped ;-)

希望有所幫助。

+0

謝謝塞巴斯蒂安!我也從提供類似代碼的作者那裏得到了回覆。 –