【问题标题】:Call third party API based off a POST call in NODEJS基于 NODEJS 中的 POST 调用调用第三方 API
【发布时间】:2022-11-14 12:13:30
【问题描述】:

我是 JS 和 NodeJs 的新手,我正在尝试创建一个 Web 服务来调用 Open Weather API 以获取当前天气。但是,我必须进行两次 POST 调用才能看到结果。我想我有点理解为什么会这样,但不知道如何解决它。

发布电话

    router.get("/", (request, response) => { 
    response.json({
       CurrentTemp: currentTemp,
       maxTemp: maxTemp,
       lowTemp: lowTemp,
       city: city,
       weather: weather
    })
})

API调用函数

function forecast () { 

    var url = `http://api.openweathermap.org/data/2.5/weather?`
            +`q=${userCity}&appid=${API_KEY}`

        requestWeather({ url: url, json: true }, function (error, response) { 

        if (error) { 
            console.log('Unable to connect to Forecast API'); 
        } 
          else { 

            currentTemp = response.body.main.temp
            maxTemp = response.body.main.temp_max 
            lowTemp = response.body.main.temp_min
            city = response.body.name
            weather = response.body.weather

        } 
    }) 
    
}

【问题讨论】:

  • forecast 是异步的。它应该得到一个在forecast 完成时触发的回调,或者将所有内容切换为 promises。您不应该设置全局变量,因为它们由每个用户共享,并且您正在覆盖不同用户的结果

标签: javascript node.js api


【解决方案1】:

您可以使用 Axios 发出 HTTP 请求

要在 node.js 中安装,您可以查看: https://www.npmjs.com/package/axios

使用 axios 的示例邮政要求 :

axios({
  method: 'post',
  url: 'url',
}).then((res) => console.log(res)).catch(err => console.log(err));

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 2020-10-25
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2016-01-02
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多