[英]Destructuring and property shorthand error
我是 node 的新手,我正在研究解構。 我想從weather-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)
問題在於,當出現錯誤時,您仍在嘗試解構數據:
request({url, json: true}, (error, {body={}})=>{
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^
但是在錯誤的情況下,數據還沒有到達,而是你得到了undefined
。 您不能解構undefined
或null
。
您有兩個選擇:
使用普通參數,然后在知道沒有錯誤后進行解構:
request({url, json: true}, (error, response)=>{ if (error) { // ... return; } const {body = {}} = response; // ... });
為整個參數提供默認值,而不僅僅是body
:
request({url, json: true}, (error, {body={}} = {})=>{ // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^ // ... });
這樣,如果您傳遞了undefined
,您將改為解構{}
。 並且由於如果對象上不存在body
則您已經默認了body
,因此該默認值將生效。
問題是,當你沒有連接到互聯網,或者你沒有得到預期的響應結構時,該函數的第二個參數是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 || {};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.