【问题标题】:JSON.stringify losing properties - Logging and saving all javascript eventsJSON.stringify 丢失属性 - 记录和保存所有 javascript 事件
【发布时间】:2019-07-13 04:31:10
【问题描述】:

我正在尝试记录并保存用户会话中发生的所有事件。

为了做到这一点,我有一个数组

var events = []

每个事件都有一个监听器..

window.onload = function() {
    window.addEventListener("abort", handleEvent);
    window.addEventListener("blur", handleEvent);
    [...]
}

并发送事件:

function sendEvents() {
    axios.post('/api/logger', JSON.stringify(events));
}

问题是每个 sendEvents() 都在发送一个事件数组,但每个事件只有两个属性:

[{"isTrusted":true,"date":"2019-02-19T14:59:42.474Z"},{"isTrusted":true,"date":"2019-02-19T14:59:42.485Z"}

但它应该有更多的属性,例如:

*altKey: false
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 662
clientY: 273
composed: true
ctrlKey: false
currentTarget: null
date: Tue Feb 19 2019 12:08:38 GMT-0300 (hora estándar de Argentina) {}
defaultPrevented: false
detail: 0
eventPhase: 0
fromElement: null
isTrusted: true
layerX: 662
layerY: 273
metaKey: false
movementX: 0
movementY: 0
offsetX: 662
offsetY: 273
pageX: 662
pageY: 273
path: (7) [header.App-header, div.App, div#root, body, html, document, Window]
relatedTarget: null
returnValue: true
screenX: 662
screenY: 400
shiftKey: false
sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false}
srcElement: header.App-header
target: header.App-header
timeStamp: 1605.000000000473
toElement: header.App-header
type: "mouseover"
which: 1
x: 662
y: 273*

即使我不对数组进行字符串化,在后端对象也只有相同的两个属性。 (我正在使用 nodejs + mongodb)

如何保存整个事件对象及其所有属性?

【问题讨论】:

  • handleEvent 是做什么的?
  • const handleEvent = e => { e.date = new Date(); events.push(e);
  • 我的意思是,它只是添加当前日期并将对象推送到数组中

标签: javascript json mongodb mongoose


【解决方案1】:

这可能有几个原因。很可能是这些属性不可枚举,导致它们不包含在 JSON 中。 (属性通过Object.defineProperties 定义为enumerable。)参见:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description

我建议明确声明要发布的属性,因为您可能并不需要所有这些属性:

axios.post('/api/logger', JSON.stringify(events.map(event=>{
  return {
    altKey: event.altKey,
    bubbles: event.bubbles,
    // etc...
  }
}));

【讨论】:

  • 是的,他真的很幸运有约会,我刚刚测试并得到了只有{"isTrusted":true}。他也应该警惕TypeError: cyclic object value 错误
  • 完美运行。这就是问题所在,这些属性是不可枚举的,所以 json.stringify 会忽略它。谢谢!
猜你喜欢
  • 2019-06-10
  • 2021-09-07
  • 2016-07-12
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
相关资源
最近更新 更多