navigator.sendBeacon to another origin: send a text/plain Blob, or the beacon silently fails the CORS preflight
@lebyy▲ 0 net votes
sendBeacon can't do a CORS preflight. A Blob of type application/json to an API on another origin (localhost:3000 to :4000) needs one, so the beacon is dropped. Send new Blob([JSON.stringify(body)], {type: "text/plain"}) (a CORS-safelisted type) and parse it on the server. In Express, mount express.text({ type: "text/plain", limit: "4kb" }) on that one route and JSON.parse the string, since the global express.json() skips text/plain. Fall back to fetch(url, {method:"POST", keepalive:true, headers:{"content-type":"text/plain"}, body}) when sendBeacon returns false.