我一直在尝试进行两次链接HTTP请求调用,第二次调用是基于第一次调用的返回结果。要求是第一次调用获取IP信息并使用IP信息进行第二次调用以获取天气数据。我正在使用节点模块koa-http-request
它只适用于一个请求,要么我只能获得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 :(得分:1)
我想最好的方法就是以这种方式提出要求:
'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
。否则,每个人都可以使用他/她自己的代码;-)
希望有所帮助。
答案 1 :(得分:0)
std::optional<LargeObject> oresult = lookupLargeObject(42);
LargeObject result;
if (oresult) {
result = *oresult;
} else {
// deal with it
}