2

For some reason, my server keeps returning undefined when ever I send an image using form data via fetch. Here's my code for the front end:

 let formData = new FormData()
let uri = "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Ftrivia-b38a8724-1083-4c3b-9706-78eed8b14ff9/ImagePicker/ff04888e-8619-420d-b80f-3ed97cebc25c.png"
const filetype = uri.split('.').pop()
let photoData = {
  name: `photo.${filetype}`,
  uri,
  type: filetype
}
formData.append('photo', photoData)
fetch('myUrl.com/upload', {
    method: 'POST',
    body: formData,
    headers:{
      'Accept': 'application/json',
      'Content-Type': 'multipart/form-data'
    },
  }).then(res => res.json())

And here is the code for the backend:

const express = require("express");
const app = express();
const http = require('http').createServer(app)
let router  = express.Router()
const multer = require('multer')
const storage = multer.memoryStorage()
const multerUploads = multer({storage})

app.use(bodyParser.json())
const PORT = process.env.PORT || 3000



app.use((req, res, next) =>{
console.log(new Date().toString())
next()
})


router.post('/upload', multerUploads.single('photo'), (req, res) =>{
console.log(req.file)
})

app.use(router)
http.listen(PORT, () => console.log(`Server started at port ${PORT}`))

What could be so wrong with it??

EchoEye
  • 51
  • 2
  • 7

1 Answers1

0

Just remove 'Content-Type': 'multipart/form-data'. Your example will looks like

fetch('myUrl.com/upload', {
    method: 'POST',
    body: formData,
    headers:{
      'Accept': 'application/json',
    },
  }).then(res => res.json())
Mher
  • 985
  • 9
  • 23