Kalviz
Kalviz

Reputation: 43

How to Post "multipart/form-data" Form and get the Text field values from the Node.js server?

Í'm trying to upload a file using multer. I can upload the file but somehow unable to get the text box values inside the form with the content/type "multipart/form-data".

<div class="container">
    <h1>File Upload</h1>
    <form action="/upload" method="POST" enctype="multipart/form-data" >
      <div class="file-field input-field">
        <div class="btn grey">
          <span>File</span>
          <input name="myImage" type="file" multiple="multiple"> 
        </div>
        <div class="file-path-wrapper">
          <input class="file-path validate" type="text">
        </div>        
      </div>
      <div ><input type="text" name="test"/></div>
      <button type="submit" class="btn">Submit</button>
    </form>
</div>

How can I get the value of the textbox

<div ><input type="text" name="test"/></div>

using body.parser? when I try

const {test} = req.body;

it gives an error TypeError: Cannot read property 'test' of undefined.

Upvotes: 2

Views: 3286

Answers (2)

Atiq Baqi
Atiq Baqi

Reputation: 652

use app.use(express.json()) instead since bodyParser was added back to Express in release 4.16.0, because people wanted it bundled with Express. That means you don't have to use bodyParser.json() anymore if you are on the latest release. You can use express.json() instead.

Upvotes: 1

baza92
baza92

Reputation: 344

You need to include body parser to your node server:

const bodyParser = require('body-parser');
app.use(bodyParser.json());       
app.use(bodyParser.urlencoded({ extended: true})); 

Then you should have access to form data in body i.e. req.body.test.

Upvotes: 1

Related Questions