【问题标题】:Destructuring and property shorthand error解构和属性简写错误
【发布时间】:2020-12-19 17:34:48
【问题描述】:

我是 node 新手,我正在处理解构。我想从天气 api 的响应中获取 body 属性并对其进行解构。当我连接到互联网时,代码工作正常,但是当我断开互联网时,代码崩溃并抛出错误。

这是我写的代码

```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, json: true}, (error, {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)

【问题讨论】:

    标签: javascript node.js ecmascript-6 destructuring


    【解决方案1】:

    问题是,当你没有连接到互联网,或者你没有得到预期的响应结构时,该函数的第二个参数是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 || {};
    }
    

    【讨论】:

      【解决方案2】:

      问题在于,当出现错误时,您仍在尝试解构数据:

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

      但是在错误的情况下,数据还没有到达,你得到了undefined。你不能解构undefinednull

      你有两个选择:

      1. 使用一个普通的参数,一旦你知道你没有错误就解构:

         request({url, json: true}, (error, response)=>{
             if (error) {
                 // ...
                 return;
             }
             const {body = {}} = response;
             // ...
         });
        
      2. 为整个参数提供默认值,而不仅仅是body

         request({url, json: true}, (error, {body={}} = {})=>{
         // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^
             // ...
         });
        

        这样,如果您传递了undefined,您将改为解构{}。并且由于您已经默认 body 如果它在对象上不存在,那么该默认值将生效。

      【讨论】:

      • 我知道您可能正在回答这个问题,所以我首先发布了一个关于问题所在的简短回答,然后添加了如何解决它(所以我可以成为第一个)! ;p
      猜你喜欢
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 2019-11-25
      • 2013-11-18
      • 1970-01-01
      相关资源
      最近更新 更多