问题描述
我是Node的新手,并且正在从事销毁工作。我想从天气API的响应中获取车身属性并将其破坏。当我连接到Internet时,代码工作正常,但是当我断开Internet连接时,代码崩溃并抛出错误。
这是我编写的代码
```const request = require('request')
const geocode = (address,callback)=>{
const url = "https://api.mapBox.com/geocoding/v5/mapBox.places/" +encodeURIComponent(address)+ ".json?access_token=theKeyHere"
request({url,json: true},(error,{body})=>{
if(error){
callback('Uh! Oh,Unable to connect with location service',undefined )
} else if (body.features.length ===0 || body.message){
callback(`Uh! Oh,Can't find location. Try another search`,undefined)
} else {
callback(undefined,{
latitude: body.features[0].center[1],longitude: body.features[0].center[0],location_Name: body.features[0].place_name
})
}
})
} ```
我得到的错误
request({url,{body={}})=>{
^
TypeError: Cannot read property 'body' of undefined
at Request._callback (F:\nodejs\weatherApp\utils\geocode.js:6:41)
at self.callback (F:\nodejs\weatherApp\node_modules\request\request.js:185:22)
at Request.emit (events.js:315:20)
at Request.onRequestError (F:\nodejs\weatherApp\node_modules\request\request.js:877:8)
at ClientRequest.emit (events.js:315:20)
at TLSSocket.socketErrorListener (_http_client.js:426:9)
at TLSSocket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processticksAndRejections (internal/process/task_queues.js:84:21)
解决方法
问题是当出现错误时,您仍在尝试对数据进行解构:
request({url,json: true},(error,{body={}})=>{
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^
但是在错误的情况下,数据尚未到达,而您却得到了undefined
。您无法破坏undefined
或null
。
您有两个选择:
-
使用普通参数,然后在知道没有错误的情况下对其进行分解:
request({url,response)=>{ if (error) { // ... return; } const {body = {}} = response; // ... });
-
为整个参数提供默认值,而不仅仅是
body
:request({url,{body={}} = {})=>{ // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^ // ... });
这样,如果您通过了
undefined
,则将破坏{}
的结构。并且由于您已经默认了body
(如果该对象上不存在该默认值),则该默认值将生效。
问题是,当您未连接到Internet或未获得预期的响应结构时,该函数的第二个参数为undefined
。所以您实际上是想这样做:
undefined.body
当然是错误的
您可以做两件事来解决它:
// - this will guarantee that the second argument will always default to
// an empty object. this way,you will not get an error
(error,{ body={} } = {}) => {
或
(error,response) => {
let body = {};
if (response) body = response.body || {};
}