Friday, 21 April 2017

Using FormData to send json file to server api

I would like to send JSON file from react component (client side) to node.js api (serve side) This is what I have got so far

dropHandler (event) {
  const fileUpload = event.target.files[0]

  let formData = new FormData()
  formData.append('file', fileUpload)

  fetch('/exchange', {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
    },
    body: formData
  })

render() {
  return (
   <input type="file" ref="file" accept=".json" onChange={this.dropHandler} />
  )
}

server.js

app.use(bodyParser.urlencoded({extended: true}))

app.post('/exchange', (req, res) => {
  console.log(req.body)
})

When I console.log(req.body) this is what i get.

{ '------WebKitFormBoundaryxfzG2GpzRt6OT4nP\r\nContent-Disposition: form-data; name': '"file"; filename="money.json"\r\nContent-Type: application/octet-stream\

r\n\r\n{\r\n  "people": [\r\n    {\r\n      "name": "John",\r\n      "year": 25\r\n    },\r\n    {\r\n      "name": "Sara",\r\n      "year": 18\r\n    },\r\n
  {\r\n      "name": "Jack",\r\n      "year": 29\r\n    }\r\n  ]\r\n}\r\n\r\n------WebKitFormBoundaryxfzG2GpzRt6OT4nP--\r\n' }

I just wanna take "name" and "age" from this object and save the values to database. If I try to console.log(req.body.people) I get undefined.

This is the JSON object that i upload through my input type="file"

{
  "people": [
    {
      "name": "John",
      "year": 25
    },
    {
      "name": "Sara",
      "year": 18
    },
    {
      "name": "Jack",
      "year": 29
    }
  ]
}



via Igor-Vuk

No comments:

Post a Comment