Home > front end >  fetch(url, {method:HEAD}) gives CORS error only if file doesn't exist
fetch(url, {method:HEAD}) gives CORS error only if file doesn't exist

Time:05-03

I need to check if a list of files is present on a server. When running this code

const promises = sentences.map(sentence => {
        return fetch(`https://.../${sentence.id}.mp3`, {
            method: 'HEAD',
            cache: 'no-store',
        })
    })

    const responses = await Promise.all(promises)

    const notFound = responses.filter(response => !response.ok)

And having set the .htaccess file in the directory to

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET "

The response status for a file that exists is 200, but for the files that doesn't exist there's still the CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource. which prevents the function to finish.

Is this due to the 404 "Not Found - The requested URL was not found on this server." redirection? How can I prevent this?

CodePudding user response:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET "

To set these headers on non-200 responses (ie. 404s), you need to use the always condition. For example:

Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Methods: "GET "

Reference:

  • Related