【发布时间】:2018-08-31 01:55:15
【问题描述】:
在选项卡\浏览器关闭时,我需要将数据发送到服务器。我发现this answer(基于this blog)推荐使用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 中,服务器端可以接受?
【问题讨论】:
-
@KevinB,问题已澄清
-
是的,我不明白其中的变异/任何部分,如果它导致发送 ajax 请求,可以使用 sendBeacon 完成。
标签: javascript graphql apollo graphql-js