Home > Software design >  Post request form data not received on express backend
Post request form data not received on express backend

Time:10-26

I tried making a form that was supposed to submit a file to an express backend but for some reason in the backend, I am not receiving the data when I submit the form.

On using console.log I get {} for req.body and undefined for sampleFile

Here is the html form,

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8" />
  <meta
   http-equiv="X-UA-Compatible"
   content="IE=edge" />
  <meta
   name="viewport"
   content="width=device-width, initial-scale=1.0" />
  <link
   rel="stylesheet"
   href="./styles/styles.css" />

  <title>Upload </title>
 </head>

 <form
  ref="uploadForm"
  name='uploadForm'
  id="uploadForm"
  action="http://localhost:4000/partners"
  method="post"
  encType="multipart/form-data">
   <input
     id="upload" type='file'  name="input1"
     placeholder="Upload file"  />
   <button type="submit">Submit</button>
  </form>
 </body>
</html>

And this is the express backend route handling the post request,

import express from 'express'
const app = express()
app.use(express.urlencoded({extended: true}))
app.post('/partners', async function (req, res) {
  console.log(req.body, '>>>>>>>body')
  console.log(req.files, '>>>>>>>files')
  
})
app.listen(4000, () => console.log('Server running on port 4000'))

CodePudding user response:

To process file uploads you need a multipart encoder for Express. You can use the Multer middleware library for that.

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

const app = express()

app.post('/partners', upload.single('partner'), function (req, res, next) {
  // req.file is the `partner` file
  // req.body will hold the text fields, if there were any
})
  • Related