问题
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=***', null, {
'User-Agent': 'koa-http-request'
});
console.log(ctx.request);
ctx.body = weatherObject;
});
app.listen(process.env.PORT || 8090);
回答1:
I guess the best way would be to make both request this way:
'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);
One more hint: edit your stack overflow question and remove your appid
from the source-code. Otherwise everyone can use your aped in his/her own code ;-)
Hope that helps.
回答2:
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);
来源:https://stackoverflow.com/questions/43399214/chaning-two-http-request-with-koa-js