Fetch API 无法加载 localhost:(端口&路径)。不支持 URL 方案“localhost”

Mon*_*xyd 19 c# fetch reactjs

我创建了使用 Spring Boot 创建的 API 的 React 应用程序。

我想通过我的反应应用程序中的表单将文件发送到服务器(服务器运行良好,因为我可以在 Postman 中上传文件)。

这是我的表格:

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

uploadFilechangeHandler方法:

 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])
    }
Run Code Online (Sandbox Code Playgroud)

当我提交此表格时,我得到以下信息:

Fetch API cannot load localhost:8080/courses/18/comments/1/img. URL scheme "localhost" is not supported.
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题呢 ?

Kav*_*ika 46

您必须按如下方式指定 URL。

http://localhost:8080/courses/1/comments/1/img
Run Code Online (Sandbox Code Playgroud)


Cod*_*ker 10

您可能忘记在 URL 中指定 http 协议。

因此,将localhost:8080/courses/1/comments/1/imgfetch 方法替换为http://localhost:8080/courses/1/comments/1/img

fetch(`http://localhost:8080/courses/1/comments/1/img`, {
    method: 'post',
    body: formData
})
Run Code Online (Sandbox Code Playgroud)