【问题标题】:API Endpoint URLAPI 端点 URL
【发布时间】:2019-10-16 06:41:34
【问题描述】:

基本上是天气 API; Apixu 最近将所有内容都更改为 weatherstack,包括他们的端点,我需要帮助更新我的 twitter 天气机器人。

我确实浏览了文档,更改为 axios,但我不断收到“无法读取属性错误”

我的旧 API 设置

   const Twit = require('twit');
   const config = require('./config');
   const rp = require('request-promise-native');

async function setup(location) {
    const options = {
    url: "http://api.apixu.com/v1/current.json",
    qs: { 
          key: API_KEY,
          q: location
        },
    json: true
};
    let result = await rp(options);
    let condition = result.current.condition.text;
    let tweetText = `The condition in ${location} is currently ${condition}!`;
    console.log("TWEETING : ", tweetText);
    sendTweet(tweetText)
}

根据他们的文档,这是应该的,但我不断收到未定义的错误。

   const params = {
   access_key: 'YOUR_ACCESS_KEY',
   query: 'New York'
}

axios.get('https://api.weatherstack.com/current', {params})
   .then(response => {
   const apiResponse = response.data;
   console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
   }).catch(error => {
   console.log(error);
  });

新的基本 URL:新的 API 请求以:

http://api.weatherstack.com/

文档:https://weatherstack.com/quickstart

UnhandledPromiseRejectionWarning:TypeError:无法读取属性'c 未定义的条件

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这 错误源于在没有捕获的情况下抛出异步函数内部 阻止,或拒绝未使用 .catch() 处理的承诺。 (拒绝 编号:1)

【问题讨论】:

  • result.current 未定义。检查你的result是否有数据??

标签: javascript node.js twitter


【解决方案1】:

我会检查 response.data.error 对象,如果出现问题,它将被填充。有趣的是,对于某些错误情况,http 状态码仍然是 200。

axios.get('https://api.weatherstack.com/current', {params})
    .then(response => {
        if (!response.data.error) {
            const apiResponse = response.data;
            console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
        } else {
            console.log(`Response error: code: ${response.data.error.code}, info: ${response.data.error.info}`)
        }
    }).catch(error => {
        console.error("An error occurred: ", error);
    }
);

使用免费套餐时,我收到以下请求错误:

Response error: code: 105, info: Access Restricted - Your current Subscription Plan does not support HTTPS Encryption.

只需更改为 http 即可轻松解决此问题(这将不太安全!):

axios.get('http://api.weatherstack.com/current', {params})
    .then(response => {
        if (!response.data.error) {
            const apiResponse = response.data;
            console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
        } else {
            console.log(`Response error: code: ${response.data.error.code}, info: ${response.data.error.info}`)
        }
    }).catch(error => {
        console.error("An error occurred: ", error);
    }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多