A
A
atumbochka2021-05-23 10:20:01
Express.js
atumbochka, 2021-05-23 10:20:01

Why is req.body not defined?

The site has the following code that sends a file to the server:

const uploadFile = target.files[0];
    console.log(uploadFile)

    const formData = new FormData()
    formData.append('upload', uploadFile)

    console.log(formData)

    const response = await fetch('upload', {
        method: 'POST',
        body: formData
    })

Here is the code on the server that accepts it:
app.post('/upload', upload.single('upload'), (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*")
  res.send(JSON.stringify({id: req.fileUploadId, name: req.fileUploadName }))
})

But as soon as I send not a file, but an array with files, nothing works: I change the line on the site:
const uploadFile = target.files;
And on the server I want, at least, to simply print the name of the first file in the array to the console: What I get is undefined. I tried a lot of things, so far I can not solve the problem. Everything works with HTML, on the site itself this array (which I send) is filled with the selected files. UPD: by the way, if you display not a name, but just an array, that is: Then we will get [object FileList], that is, an array with files is sent, but if I just want to find out the name of one of the files, or any other parameter, then I get undefined
console.log(req.body.upload[0].name)

console.log(req.body.upload)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2021-05-24
@Lynn

https://github.com/expressjs/multer/blob/master/do...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question