gpt4 book ai didi

javascript - Node : Cannot read property 'length' of undefined

转载 作者:行者123 更新时间:2023-11-30 13:50:50 28 4
gpt4 key购买 nike

当我在 nodejs 中运行 node app.js 时,错误消息显示“无法读取未定义的属性‘长度’”。我已经安装了所有相关的库(例如请求)并查看了不同的相关帖子。但是,问题仍然存在。

请你告诉我如何解决它。非常感谢!

Windows 10 家用电脑 Visual Studio Code

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

geocode('Boston', (error, data) => {
console.log('Error', error)
console.log('Data', data)
forecast(data.latitude, data.longitude, (error, data) => {
console.log('Error', error)
console.log('Data', data)
})


})

// forecast.js
const request = require('request')

const forecast = (latitude, longitude, callback) => {
const url =
'https://api.darksky.net/forecast/9d1465c6f3bb7a6c71944bdd8548d026/' +
latitude + ',' + longitude

request({ url: url, json: true }, (error, response) => {
if (error) {
callback('Unable to connect to weather service!', undefined)
} else if (response.body.error) {
callback('Unable to find location', undefined)
} else {
callback(undefined, response.body.daily.data[0].summary + ' It is
currently ' + response.body.currently.temperature + ' degress out. There
is a ' + response.body.currently.precipProbability + '% chance of rain.')
}
})
}

module.exports = forecast


// geocode.js
const request = require('request')

const geocode = (address, callback) => {
const url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' +
address + '.json?access_token=pk.eyJ1IjoiYW5kcmV3bWVhZDEiLCJhIjoiY2pvOG8ybW90MDFhazNxcnJ4OTYydzJlOSJ9.njY7HvaalLEVhEOIghPTlw&limit=1'

request({ url: url, json: true }, (error, response) => {
if (error) {
callback('Unable to connect to location services!', undefined)
} else if (response.body.features.length === 0) {
callback('Unable to find location. Try another search.',
undefined)
} else {
callback(undefined, {
latitude: response.body.features[0].center[0],
longitude: response.body.features[0].center[1],
location: response.body.features[0].place_name
})
}
})
}

module.exports = geocode

我希望看到波士顿,它的纬度和经度。

最佳答案

在检查features长度之前,还可以检查features是否存在:

else if (response.body.features && response.body.features.length === 0) {

关于javascript - Node : Cannot read property 'length' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58270020/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com