2017-04-13 71 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

谢谢塞巴斯蒂安!我也从提供类似代码的作者那里得到了回复。 –