Recover key value added in formData in backend

Asked

Viewed 94 times

-3

Guys I have the following request on frontend

  formData.append("file", this.file);
  formData.append("name", "test");

  axios
    .post(`${baseApiUrl}/exame`, formData)

In the backend I can recover the value of the "file" field with this function:

const upload = multer({ dest: 'uploads/' }).single("file")

function save(req, res) {
    upload(req, res, function (err) {
        console.log(req.file) // Acesso ao conteúdo de file
        console.log(req.name) // Undefined :(
    })
}

However my question is, how do I recover the field "name" and other in case I decide to add?

NOTE: I am calling the upload function this way because I need to capture the errors (if they exist) when recording the file, according to the documentation doc multer

1 answer

0

The correct is req.body to pick up the contents of a POST, so that would be it:

console.log(req.body)

Now if you are using multer and actually want to get work uploading a single file should do something like:

const upload = multer({ dest: 'uploads/' })

app.post('/profile', upload.single('file'), function (req, res, next) {
  console.log("arquivo", req.file) is the `avatar` file
  console.log(req.body)
})

It feels wrong here: upload(req, res, function (err) { and you wrote the return inside the third parameter of the mutler object, when it should be the third parameter of the app object in the method . post()


If multiple upload:

const upload = multer({ dest: 'uploads/' })

app.post('/photos/upload', upload.array('file', 12), function (req, res, next) {
     console.log(req.files);
     console.log(req.body);
})

That’s assuming you’re using Express

  • Hello Uilherme, thanks for helping! In case I used this way because I need to capture the errors when saving the file (if any), as shown link. About the req.body it always comes as Undefined :/

  • @Rectiorts this was not informed in the question, it seemed more a typo, this you should always explain. I will edit

  • Really, I forgot to mention it. Thanks, I’m on hold :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.