在选项卡\浏览器关闭时,我需要将数据发送到服务器。我发现了这个答案 (基于这个博客),它建议使用sendBeacon。这里将向您展示如何准备数据,以便通过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中呢?
发布于 2018-03-22 00:19:41
在使用按钮而不是Blob的帮助下,找到了为什么unload不能工作的原因。问题在于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类型的请求,根据从错误链接,这是不安全的。
对于Firefox,可以使用Django的包corsheaders修复这个问题,并将CORS_ALLOW_CREDENTIALS = True添加到设置中。
https://stackoverflow.com/questions/49414923
复制相似问题