I have a simple node.js server that serves and plays an audio file when a user clicks a button. Here is the simplified version of my code for the backend:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/audioSync', (req, res) => {
const headers = {
"Content-Type" : "audio/ogg",
"Cache-Control" : "no-cache",
"Expires" : 0
};
res.set(headers);
res.sendFile('/path/to/file/input.ogg');
});
And the front end:
let audio;
const playBtn = document.getElementById('play');
const pauseBtn = document.getElementById('pause');
playBtn.addEventListener('click', (e) => {
audio = new Audio('/audioSync');
audio.play();
});
pauseBtn.addEventListener('click', (e) => {
audio.pause();
});
Ideally what I would like to happen here is for the frontend to make a new http request for the audio file every time the play button is clicked. This is because in my actual app, the /audioSync endpoint does not return the same audio file, and a fresh request has to be made in order to make sure that the correct file is received.
However, I cannot get the browser to do this. The problem is that the browser is caching the audio file, so it will not make a new request because it thinks it already has the file it needs despite the fact that I am including the "Cache-Control" : "no-cache" and "Expires" : 0 header on my response. It appears that the decision to even construct the request is not handled by the browser's http module, but instead by whichever module is responsible for procuring files using the html src attribute. I think this because when I inspect the network requests in the browser, the first time the button is pressed, the browser makes the request. But every subsequent time, there is no request even being made until a certain timeout period has been reached and the browser makes the request again. This is different from a cached http request which appears greyed out, and these can be disabled by clicking the disable cache option. This leads me to believe that there are two separate caches for media files and http requests, and I can only affect the latter with http headers.
So my question has three parts: am I correct in assuming this? is there any interface that I can use to affect how the browser requests the file (something that would force a new request to be made)? Is this media cache open to Javascript through a WebAPI?
In my research, I have come across some stack overflow questions like this, and the answers all circle back to cache busting of some sort, where a random query string is included in the endpoint to trick the browser into making the request again. I am asking this question again because many of these posts happen to be quite old or they simply tell you to change the Cache-Control header, and I am wondering if a more modern, elegant solution has been implemented since, particularly a front end solution that forces a new request.
Thank you