A
A
atumbochka2021-04-15 12:27:18
JavaScript
atumbochka, 2021-04-15 12:27:18

How to solve fetch problem?

The essence of the program is that the user uploads his file, after which he is given a link to download it, here is the code that is responsible for this:

fileControl.addEventListener('change', async function(event){
    const target = event.target;

    const uploadFile = target.files[0];
    console.log(uploadFile);

    const formData = new FormData()
    formData.append('upload', uploadFile)

    const response = await fetch('upload', {
        method: 'POST',
        body: formData
    })

    const data = await response.json();
    console.log(data);

    const link = document.createElement('a');

    link.href = '/file/' + data.id;
    link.textContent = uploadFile.name

    content.appendChild(link);

});


After downloading the file, the link does not appear, and the console outputs the following: Fetch API cannot load file:///C:/Users/123/Desktop/express%20test/expres... . URL scheme must be "http" or "https" for CORS request.

And to be honest, I don't understand if the problem is CORS or the file path. I put in the server file, but nothing changed, apparently something is wrong with the paths.
res.setHeader("Access-Control-Allow-Origin", "*")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MikUrrey, 2021-04-15
@MikUrrey

Your call to the server is written as This means that it will substitute `upload` in the URL of the page and try to upload the file there. And this, in turn, means that the page opened by a click from the explorer will pass an invalid URL to the fetch function. For everything to work, the page must be placed on the same domain where the server is running and opened by typing the address in the browser so that the URL in the address bar does not start with file://, but with http://
await fetch('upload', ...)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question