【问题标题】:How to make an API request with another API result in NodeJS?如何在 NodeJS 中使用另一个 API 结果发出 API 请求?
【发布时间】:2019-11-06 16:35:14
【问题描述】:

我想用上一个 API 的数据创建另一个 API,但我不知道如何使用 axios 发出多个请求。我尝试了一些东西,但它没有显示任何东西。我想显示上一个 API 的路线数据。

这是为了制作另一个最简单的API。

async function temperature() {

    this.start = '2017-01-01';
    try {
        this.latlongdata = await axios.get('https://api.apixu.com/v1/current.json?key=' + WEATHER_KEY + '&q=' + 'navodari');
        this.lat = latlongdata.data.location.lat;
        this.lon = latlongdata.data.location.lon;
        console.log(lat);

        this.stationdata = await axios.get('https://api.meteostat.net/v1/stations/nearby?lat=' + this.lat + '&lon=' + this.lon + '&limit=1&key=' + STATION_KEY);
        this.station = stationdata.data.data[0].id;

        this.tempdata = await axios.get('https://api.meteostat.net/v1/history/daily?station=' + this.station + '&start=' + this.start + '&end=' + this.start + '&key=' + STATION_KEY);
        return this.tempdata;

    } catch (err) {
        console.log(err);
    }
};

class WeatherController {

    index ({ response }) {
        response.send(temperature());
    }
}

module.exports = WeatherController

我想显示来自this.tempdata 的整个 API。

【问题讨论】:

  • “这不起作用。” - 它怎么不工作?是否报告了任何错误?
  • 哦,抱歉,我会解决这个问题,它没有在屏幕上显示任何内容。整个页面是空白的。
  • WheatherController 是如何使用的?请注意 temperature() 返回一个承诺 - 也许 response.send 无法处理?
  • WeatherController 是我主机上的路由 'const vreme = '/vreme' Route.get(vreme, 'WeatherController.index')'
  • 您需要使用调试器逐步完成它。您的浏览器控制台中是否显示任何内容?

标签: node.js api async-await request axios


【解决方案1】:

前言:鉴于 asyncPromise<T> 使得在 JavaScript 中正确使用类型变得更加重要,这很好地说明了为什么更多的程序员应该使用 TypeScript。

简短的回答:你从temperature()返回一个Promise<T>(我假设Tobject),然后将它传递给ExpressJS的Response.send函数,但send不接受Promise对象。

Response.send 函数接受 Buffer | String | Array | object 类型的单个参数。这在此处记录:https://expressjs.com/en/api.html#res.send (虽然 技术上 Promise<T>object,但它不是具有可枚举属性的 JSON 样式对象,这是 send 所期望的).

解决方法很简单:首先将您的 Controller 操作更改为 await temperature() 结果(即解析 tempdata 对象),然后再将其传递给 response.send

async index( { response } ) {
    let temperatureData = await temperature();
    response.send( temperatureData );
}

不相关的评论: * 你不应该在你的temperature() 函数中使用this. 存储本地值,因为它会在你的程序中引入与并发相关的错误。始终避免改变共享状态。 * 你应该将temperature() 函数重命名为getTemperature(),甚至getTemperatureAsPromise() 以非常清晰,以便用户知道如何使用它,因为你不使用JSDoc 或TypeScript。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2020-03-24
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多