如何修复Uncaught(承诺)SyntaxError:JSON输入意外结束?

时间:2019-04-30 17:45:19

标签: reactjs post file-upload form-data cloudinary

所以我想使用React将文件上传到Cloudinary,但是在我的Upload.js:22 Uncaught (in promise) SyntaxError: Unexpected end of JSON input行中得到了let json = await res.json();。我该如何解决?

class Upload extends React.Component {
  processFile = async e => {
    var file = e.target.files[0];
    var formdata = new FormData();

    formdata.append("file", file);
    formdata.append("cloud_name", "dvrmt2oir");
    formdata.append("upload_preset", "wco0c7sr");

    let res = await fetch(
      "https://api.cloudinary.com/v1_1/dvrmt2oir/image/upload",
      {
        method: "post",
        mode: "cors",
        body: formdata
      }
    );

    let json = await res.json();
    console.log(JSON.stringify(json.secure_url));
  };

  render() {
    return (
      <div>
        <h3>Upload</h3>
        <input type="file" onChange={this.processFile} />
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

我尝试使用以下代码:


import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class Upload extends React.Component {
  processFile = async e => {
    var file = e.target.files[0];
    var formdata = new FormData();

    formdata.append("file", file);
    formdata.append("cloud_name", "dvrmt2oir");
    formdata.append("upload_preset", "wco0c7sr");

    let res = await fetch(
      "https://api.cloudinary.com/v1_1/dvrmt2oir/image/upload",
      {
        method: "post",
        mode: "cors",
        body: formdata
      }
    );

    let json = await res.json();
    console.log(JSON.stringify(json.secure_url));
  };

  render() {
    return (
      <div>
        <h3>Upload</h3>
        <input type="file" onChange={this.processFile} />
      </div>
    );
  }
}
ReactDOM.render(<Upload />, document.getElementById("container"));

它奏效了。您能提供您尝试上传的图片吗?