NodeJS:无法读取未定义的属性“长度”

时间:2019-10-07 12:56:12

标签: javascript node.js

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

请您告知我该如何解决。非常感谢!

Windows 10家用PC Visual Studio代码

//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

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

似乎API返回 NULL ,因此响应正文中没有“功能” 在这种情况下,您必须检查您是否真的得到响应“ response.body.features”,然后检查长度。 这样您的情况就出现在else语句中:

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

答案 2 :(得分:0)

else if (typeof response.body.features == "undefined")

尝试