有没有办法使用 'unload\navigator.sendBeacon' + 'GraphQL' 将数据发送到服务器?

Is there a way to send data to server using 'unload\navigator.sendBeacon' + 'GraphQL'?

在 tab\browser 关闭时,我需要向服务器发送数据。我发现 this answer (based on this blog) which recommends to use sendBeacon. Here 显示了必须如何准备数据才能通过 Ajax 将它们发送到服务器。我重复了答案中的结构:

window.addEventListener('unload', this.sendDataToServer, false)

sendDataToServer () {
    myData = JSON.stringify({
    'mutation': `mutation EmailAuth($email: String!, $password: String!) {
        getOrCreateUser(email: $email, password: $password) {
        token
        }
    }
    `,
    'variables': {email: 'test@test.net', password: 'Test'}
    })

    navigator.sendBeacon('http://localhost:8000/graphql', myData)
}

在这种情况下,Django 显示:"POST /graphql HTTP/1.1" 400 53

我也在网上找到了Blob的版本:

window.addEventListener('unload', this.sendDataToServer, false)

sendDataToServer () {
    let headers = {
        type: 'application/json'
    }
    let myBlob = new Blob([JSON.stringify({
        'mutation': `mutation EmailAuth($email: String!, $password: String!) {
            getOrCreateUser(email: $email, password: $password) {
            token
            }
        }
        `,
        'variables': {email: 'test@test.net', password: 'Test'}
    })], headers)

    navigator.sendBeacon('http://localhost:8000/graphql', myBlob)
}

但在这种情况下,Django 根本没有任何反应。

如何将我在前端的数据包装成 GraphQL 格式并以 sendBeacon 的方式放入服务器端可以接受的方式?

在使用按钮而不是 unload 的帮助下找到 Blob 不起作用的原因。问题出在 chrome 浏览器上。控制台显示:Uncaught DOMException: Failed to execute 'sendBeacon' on 'Navigator': sendBeacon() with a Blob whose type is not any of the CORS-safelisted values for the Content-Type request header is disabled temporarily. See http://crbug.com/490015 for details.

Django 正在等待 application/json 类型的请求,根据 link from error 是不安全的。

对于 Firefox,可以使用 Django 的包 corsheaders 并在设置中添加 CORS_ALLOW_CREDENTIALS = True 来解决此问题。