【问题标题】:Is there a way to send data to server using 'unload\navigator.sendBeacon' + 'GraphQL'?有没有办法使用 'unload\navigator.sendBeacon' + 'GraphQL' 将数据发送到服务器?
【发布时间】:2018-08-31 01:55:15
【问题描述】:

在选项卡\浏览器关闭时,我需要将数据发送到服务器。我发现this answer(基于this blog)推荐使用sendBeaconHere 显示了必须如何准备数据才能通过 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 中,服务器端可以接受?

【问题讨论】:

标签: javascript graphql apollo graphql-js


【解决方案1】:

在使用按钮而不是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 添加到设置中。

【讨论】:

    猜你喜欢
    • 2010-09-06
    • 2019-05-27
    • 2022-01-17
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2022-10-24
    相关资源
    最近更新 更多