Thursday, 13 April 2017

Chaning two HTTP request with Koa.js

I have been trying to make two chaining HTTP requests calls, second call is based on the return result of the first call. Requirement is make the first call to get the IP information and use the IP information to make the second call to grab weather data. And I am using an node module koa-http-request

It only works with one request, either I can only get IP or I can only get Weather Data.

    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=92d2a968be86265b0a093338e8e2e0d9', null, {
            'User-Agent': 'koa-http-request'
        });
        console.log(ctx.request);
        ctx.body = weatherObject;
    });

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



via Jeremy.Xu

No comments:

Post a Comment