NodeJS API端点URL

vmpqdwk3  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(134)

基本上,天气空气污染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
UnhandledPromiseRejection警告:TypeError:无法读取未定义的属性“条件”
UnhandledPromiseRejection警告:未处理的承诺拒绝。这个错误可能是由于抛出了一个没有catch块的async函数,或者是拒绝了一个没有用.catch()处理的promise。(拒收ID:第一章

g0czyy6m

g0czyy6m1#

我会检查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);
    }
);
deikduxw

deikduxw2#

如果你使用的是免费版本,你需要使用'http'来工作,我猜如果你想使用'https',你需要购买的是premiun这里是我使用http://api.weatherstack.com/current?access_key=0a82bdc4c6628b5f968dd500d30a8857&query=19.0760,-72.8777的简单示例

相关问题