missgentle / Q-A

Web前端技术分享与疑问解答
0 stars 1 forks source link

使用fetch上传文件,控制台请求Headers中Form Data为空 #37

Open missgentle opened 4 years ago

missgentle commented 4 years ago

https://blog.csdn.net/realLiuNing/article/details/84204624

missgentle commented 4 years ago

简略代码类似如下:

<input type="file" onChange={this.handleUpload}/>

handleUpload = (e) => {
    e.preventDefault();

    let file = e.target.files[0];
    const formdata = new FormData();
    formdata.append('file', file);

    const url = 'http://127.0.0.1:8080/file/upload';
    fetch(url, {
        method: 'POST',
        body: formdata,
        //headers: {
        //    "Content-Type": "multipart/form-data"
        //}
    }).then(response => return response.json();)
      .catch(error => console.log(error));
};

在跨域请求时不能自定义头部,需要去掉headers,否则POST请求会变成OPTIONS请求。

去掉后控制台可看到Form Data有内容:
issue37