How to upload FormData using Axios?

假装没事ソ 提交于 2019-12-21 21:32:36

问题


I am trying to upload 3 photos from frontend using formData. It will call an external API to make the upload. But encountered some errors as below.

Frontend upload

 const formData = new FormData()
  formData.append('photoA', this.photoA)
  formData.append('photoB', this.photoB)
  formData.append('photoC', this.photoC)
   axios.post(`http://localhost:4172/uploadDocs`, 
      { 
          data: formData,
          accessToken: store.state.token
      },
      { headers: {
          // 'Content-Type': 'Application/json',
          // 'x-access-token': localStorage.getItem('token')
        }
      }
    ).then (function (response) {
      return response.data
    })

Nodejs upload API

async uploadDocs (req, res) {
    const options = {
        method: "POST",
        url: "https://example.com/api/v1/users/uploadDocuments?access_token=" + req.body.accessToken,
        headers: {
            //"Authorization": "Basic " + auth,
            //"Content-Type": "multipart/form-data"
        },
        data: req.body.data
    };
    try {
        request(options, function (err,response,body){
            if (err) {
                res.send(err)
            } else {
                res.send(response.body)
            }
        })
    } catch (error) {
        res.status(400).send({
            error: "Server error."
        })
    }
}

So there are 2 errors here:

a) Frontend error: It keeps giving Cannot POST / error in html

b) Backend error:

<h1>Cannot read property &#39;photoA&#39; of undefined</h1>
<h2></h2>
<pre></pre>

Been struggling with this for days. Any help will be very much appreciated.

来源:https://stackoverflow.com/questions/51814401/how-to-upload-formdata-using-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!