【非提问】老师,你好,关于const { body } = ctx.request 后续
来源:2-5 Koa开发RESTful接口,GET&POST获取数据及数据格式化方法【进阶篇】
qq_潇生落雨_0
2020-03-24 08:24:55
很久之前我问过一个我觉得很诡异的问题,就是输出对象里面没有body属性,但是却偏偏可以读取到body属性在调试的过程中也可以看到该属性。当时我不理解这种现象,因此随便的采纳了一个答复。
这个不是提问,而是填坑
如果有朋友回答了,过段时间我会找一个朋友的回答采纳的。
我不知道老师你还记不记得这个提问,希望这个回答也能解答你的疑惑。
老师,你好,关于const { body } = ctx.request
今天我找到了一个可能的答案,因此想把这个坑填上。也许ctx.request.body是一个只可读属性。
我尝试使用js复现了类似的现象,在调试时可以看到aObj,直接打印obj时没有aObj属性,但是又可以输出obj.aObj
最后附上代码,如果有朋友看过我之前提的问题,又感到疑惑的话,可以尝试验证一下,如果觉得我的回答有误,也很希望能告知我,谢谢!
var obj = { get aObj(){ return { a:'111' } } } console.log(obj) // debugger console.log(obj.aObj)
2回答
The output of console.log(anObject) is misleading; the state of the object displayed is only resolved when you expand the > in the console. It is not the state of the object when you console.log'd the object.
Instead, try console.log(Object.keys(config)), or even console.log(JSON.stringify(config)) and you will see the keys, or the state of the object at the time you called console.log.
意思是:console.log其实有误导,对象的解析通常是在我们使用console > 命令行的时候,才会获取到对象的完整体。
最靠谱的就是调试啦~~
qq_潇生落雨_0
提问者
2020-03-24
嗯,确实,这样就可以输出到keys了。虽然我还是不清楚为什么console.log具有这种特性,但至少知道之前遇到的问题不是诡异的个别现象,也有一定的规律可循,另一方面,也基本让我相信ctx.request里面是一直都有这个key的。我之前之所以想知道这个问题的答案,主要是:因为好像console.log是异步的,所以我在想会不会一开始是有这个key的,但是在执行了一些代码后,会对这个执行例如`delete ctx.request.body`将这个key删除了。如果是,为什么要这么做?现在看来,这个key一直都在,只是基于某些特性,console.log的时候没有输出到而已。
相似问题