我试图在代码中使用react-dropzone并使用axios向服务器发出POST请求,但是POST请求始终失败,并且不断出现以下错误:

未捕获( promise )错误:请求失败,状态码为500

这是我的组成部分

constructor(props) {
  super(props);
  this.state = {
    accepted: [],
  };

  ['handleChange', 'handleValidSubmit'].forEach(v => {
    this[v] = this[v].bind(this);
  });
}

handleValidSubmit(event, values) {
  const data = {
    accepted: this.state.accepted,
  };
  console.log(data);
  axios({
    method: 'post',
    url:
      'https://oc6tq8iop5.execute-api.ap-southeast-1.amazonaws.com/dev/upload',
    data: JSON.stringify(data),
  }).then(data => {
    console.log(data);
    onDrop: accepted => {
      accepted.forEach(file => {
        req.attach(file.name, file);
      });
      req.end(callback);
      var formData = new FormData();
      formData.append('gambar', values.accepted);
      console.log(formData);
    };
  });
}

handleChange(event) {
  const { target } = event;
  const value = target.type === 'checkbox' ? target.checked : target.value;
  const { name } = target;

  this.setState({
    [name]: value,
  });
}

这是我的渲染方法
<div className="dropzone">
  <Dropzone
    accept="image/jpeg, image/png, image/jpg"
    onDrop={accepted => {
      this.setState({ accepted });
    }}
    maxSize={200000}
    multiple={false}
  >
    <p>Maksimal 2 MB (JPG/PNG)</p>
  </Dropzone>
  {this.state.accepted.map(f => (
    <span key={f.name}>
      {f.name} - {f.size} bytes
    </span>
  ))}
</div>

最佳答案

您只需要使用axios发送 header ,

const config = { headers: { 'Content-Type': 'multipart/form-data' } };
let fd = new FormData();

values.map((file) => {
  fd.append('File[]',file);
});

axios.post(`${ROOT_URL}/ImageUpload`, fd, config)
  .then((response) => {
    callback(response);
  })
  .catch(error => {
      errorResponse(error);
  })

关于javascript - react dropzone无法发布与axios,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50387610/

10-13 08:23