销毁和财产简写错误

问题描述

我是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。您无法破坏undefinednull

您有两个选择:

  1. 使用普通参数,然后在知道没有错误的情况下对其进行分解:

     request({url,response)=>{
         if (error) {
             // ...
             return;
         }
         const {body = {}} = response;
         // ...
     });
    
  2. 为整个参数提供默认值,而不仅仅是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 || {};
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...