繁体   English   中英

上传文件 Api 请求在 postman 中有效,但在 nodejs 中无效并反应 MERN

[英]Upload File Api request works in postman but not in nodejs and react MERN

我正在上传文件和媒体 API,在 Postman 中工作正常,但在代码中不行

反应代码:

campaignChangedHandler = (event) => {
   this.setState(
        {
            campaignFile: document.getElementById('campaignFile').files[0]
        })
};

onSubmit = async(e) => {
   let formData = new FormData();
    formData.append('campaignFile', this.state.campaignFile);

     const headers = {
        'Authorization': `Bearer ${token}`
     };

      await axios.post('http://localhost:3001/upload/', {formData}, {headers}).then(resp => {
         console.log(resp)
      })
};


render() {
  return (
    <form onSubmit={this.onSubmit}>
        <input value={this.state.data} error={errors.data}
            onChange={this.campaignChangedHandler}
            name={"campaignFile"}
            id="campaignFile"
            type="file"/>
    </form>
  )
}

节点 JS 代码:

const fileUpload = require('express-fileupload');
app.use(fileUpload());

app.post('/upload', function (req, res) {
   console.log(req.files);
}

我总是在 Nodejs 控制台中得到 UNDEFINED,我尝试使用多方、multer、busboy,但我得到了相同的结果,但是在 postman 我得到了这个:

来自 postman 的响应

尝试这个:

constructor(props) {
    super(props);
      this.state = {
        campaignFile: null
      }

  }



 onChangeHandler=event=>{
    this.setState({
      campaignFile: event.target.files[0],
    })
  }



 onSubmit = async(e) => {
   let formData = new FormData();
   formData.append('campaignFile', this.state.selectedFile);

     const headers = {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${token}`
     };

      await axios.post('http://localhost:3001/upload/',formData,headers).then(resp => {
         console.log(resp)
      })
};


render() {
  return (
    <form onSubmit={this.onSubmit}>
        <input type="file" name="campaignFile" onChange={this.onChangeHandler}/>
    </form>
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM