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

Viewed 11504

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 ?

2 Answers

You have to specify the URL as follows.

http://localhost:8080/courses/1/comments/1/img

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
})
Related