gpt4 book ai didi

javascript - 使用 'beforeunload'/'unload' eventlistener 关闭浏览器后使用 Fetch 发送 POST 请求不起作用

转载 作者:行者123 更新时间:2023-12-05 08:14:17 25 4
gpt4 key购买 nike

对于我的生活,我无法弄清楚发生了什么。我整天都在寻找答案,但在任何地方都找不到。我正在练习编写一个函数,通过电子邮件将废弃的表单发送给我。

这是我为托管表单的本地主机运行的 index.js 文件

const inputSelector = document.getElementById("name");
const fieldSelector = document.querySelectorAll('.formfield');
let formData = {};


fieldSelector.forEach(field =>{

field.addEventListener('input', (e) =>{

let formField = e.target.id;
formData[formField] = field.value;

});
})


window.addEventListener('beforeunload', () =>{
fetch('http://localhost:8080/', {
method:'post',
headers:{
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: formData
})
})
})

请求发送到的函数是一个包含以下代码的云函数:

exports.testFetch = async (req, res) =>{
console.log(req.method);
if(req.method === 'OPTIONS'){
console.log('method is option')
res.set('Access-Control-Allow-Origin', "*")
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.set('Access-Control-Allow-Headers', 'Content-Type');
}

else{

console.log('full body: ', req.body);
console.log('message: ', req.body.message);
}

res.send('response')

}

现在,每当我填写表单字段然后从该页面浏览到另一个页面时,它都能完美运行,云函数 console.logs 表单字段。但是,当我只是通过单击 X 关闭页面时,云功能只有 console.log 'OPTIONS' 和 'method is option'。看起来它只发送发布请求的选项部分。我整个下午都在寻找解决方案,但到处都找不到。 super 令人沮丧。当我只是将获取功能添加到按钮然后按下按钮时,它也能完美运行。只是关闭浏览器,它似乎不起作用并卡在 OPTIONS 中。如果您有任何提示,请告诉我!

最佳答案

正如 Endless 的回答所讨论的,sendBeacon 是一个选项。但问题是您的提取请求未使用 keepalive flag .

Normally, when a document is unloaded, all associated network requestsare aborted. But the keepalive option tells the browser to perform therequest in the background, even after it leaves the page. So thisoption is essential for our request to succeed.

window.addEventListener('beforeunload', () => {
fetch('http://localhost:8080/', {
method:'post',
headers:{
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: formData
}),
keepalive: true // this is important!
})
})

关于javascript - 使用 'beforeunload'/'unload' eventlistener 关闭浏览器后使用 Fetch 发送 POST 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63157089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com