首页 > 解决方案 > 无法解构“未定义”的属性“纬度”

问题描述

所以我目前正在看NODE JS教程。以下内容是关于一个简单的天气应用程序。

这里的天气应用程序似乎工作正常,但每次出现无效地址时都会引发错误。

通过地理位置文件获取的坐标获取天气数据的代码(向下滚动代码)

const request=require('request')

const forecast = (latitude, longitude, callback) => {

  const url = 'https://api.darksky.net/forecast/35972b6a44cd0db6090786bed86c6ccc/'+encodeURIComponent(latitude)+','+encodeURIComponent(longitude)+'?units=si'

  request({url,json : true}, (error,{ body }) => {

    if(error){
      callback('Unable to connect to the weather service',undefined)
    }
    else if(body.error){
      callback('Unable to find location',undefined)
    }
    else {
      callback(undefined,{
        Today : body.daily.data[0].summary,
        CurrentTemperature : body.currently.temperature,
        ChanceOfRain : body.currently.precipProbability
      })
    }

  })


}

module.exports = forecast

以及将地名转换为坐标的代码

const request = require('request')


const geocode = (address,callback) => {

  const url ='https://api.mapbox.com/geocoding/v5/mapbox.places/'+encodeURIComponent(address)+'.json?access_token=pk.eyJ1IjoibWVjaHkiLCJhIjoiY2s0bDd6b2E4MGUzZjNuczh1ZngyZGFhNSJ9._ei4RZ_9ZUKJKK0xfqBj_A'
  request({url, json : true}, (error,{body}) => {

    if(error){
      callback('Unable to connect to the weather service',undefined)
    }
    else if(body.features.length===0){
      callback('Unable to find location',undefined)
    }
    else{
      callback(undefined, {
        location : body.features[0].place_name,
        longitude : body.features[0].center[0],
        latitude  : body.features[0].center[1]
      })


    }
  })
}

module.exports = geocode

和应用程序代码本身

const geocode = require('./utils/geocode')
const forecast = require('./utils/forecast')

const address = process.argv[2]

if (!address) {
    console.log('Please provide an address')
} else {
    geocode(address, (error, { latitude, longitude, location }) => {
        if (error) {
            return console.log(error)
        }

        forecast(latitude, longitude, (error, forecastData) => {
            if (error) {
                return console.log(error)
            }

            console.log(location)
            console.log(forecastData)
        })
    })
}

当我传入一个无效的地址错误图片时,我还上传了错误图片

我一周前才开始学习 NODEjs,我需要一些帮助。我希望这些信息足够了。

标签: javascriptnode.jsecmascript-6

解决方案


in geocode.js in both if and else if statements ,change statements as follows

callback('Unable to connect to the weather service',undefined || {})

推荐阅读