Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch API cannot load localhost:(port&path). URL scheme "localhost" is not supported

Tags:

c#

reactjs

fetch

I create react app that use API created with Spring Boot.

I would like to send a file to the server via the form in my react app (The server works good because I can upload file in Postman).

This is my form:

   <form onSubmit={e => uploadFile(e)} >
           <input type="file" name="img" onChange={changeHandler} />
           <button>Add!</button>
   </form>

uploadFile and changeHandler methods:

 const [selectedFile, setSelectedFile] = useState()

const uploadFile = () => {
        const formData = new FormData()
        formData.append('File', selectedFile)

        fetch(`localhost:8080/courses/1/comments/1/img`, {
            method: 'post',
            body: formData
        })
            .then(resp => resp.json())
            .then(data => console.log(data))
            .catch(err => console.log(err))
    }

    const changeHandler = (e) => {
        setSelectedFile(e.target.files[0])
    }

When I submit this form I get this:

Fetch API cannot load localhost:8080/courses/18/comments/1/img. URL scheme "localhost" is not supported.

How to solve this problem ?

like image 287
Monoxyd Avatar asked Sep 10 '25 17:09

Monoxyd


2 Answers

You have to specify the URL as follows.

http://localhost:8080/courses/1/comments/1/img
like image 131
Kavindu Vindika Avatar answered Sep 12 '25 07:09

Kavindu Vindika


You might be forgot to specify the http protocol in the URL.

So, replace localhost:8080/courses/1/comments/1/img in the fetch method with http://localhost:8080/courses/1/comments/1/img

fetch(`http://localhost:8080/courses/1/comments/1/img`, {
    method: 'post',
    body: formData
})
like image 37
Codemaker Avatar answered Sep 12 '25 09:09

Codemaker