question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

req.body appears empty half the time

See original GitHub issue

I’m having an issue with multer that has stumped me for a few days. Half the time, everything works as expected and flawlessly, and the other half of the time req.body is an empty object and req.file is undefined.

Here’s what my setup looks like:

Frontend:

  const source = {uri: image.path, isStatic: true, type: image.mime, name: image.path.split("/").pop()};
  const xhr = new XMLHttpRequest();
  let formData = new FormData();
  formData.append('userId', userId);
  formData.append('file', source);

  xhr.onreadystatechange = () => {
    if (xhr.readyState === xhr.DONE) {
      if (xhr.status >= 400) {
        alert(xhr.responseText);
      } else {
        const response = JSON.parse(xhr.response);
        if (response.success) {
          //success handler
        } else {
          //failure handler
        }
      }
    }
  };
  xhr.open('POST', `${ROOT_URL}/api/user/profile_photo`);
  xhr.send(formData);

The image object used in source is being supplied by a React Native module that selects and crops images.

My route:

    const multer = require('multer');
    const upload = multer().single('file');

    module.exports = function(app) {
      app.post('/api/user/profile_photo', upload, User.updateProfilePhoto);
    }

And Express endpoint:

    exports.updateProfilePhoto = function(req, res, next) {
      const _id = req.body.userId;
      const file = req.file;

      console.log("file", req.file);
      console.log("body", req.body);

      //S3 upload and other things
    }

I can’t for the life of me figure out what’s going wrong? It’s a pretty simple setup. I thought maybe it was a conflict with bodyParser but having tested it without bodyParser it still only works half of the time.

Any insight? I’m using v1.3.0 of multer

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:14 (7 by maintainers)

github_iconTop GitHub Comments

7reactions
dman777commented, Apr 4, 2017

Are you sure it’s not this?

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

I resolved my issue by reversing the order of my form object properties in the front end:

        var newFormObj  = new FormData();
        newFormObj.append('internalUserID', internalUserID);
        newFormObj.append('listingImage', this.binaryImages[image]);
2reactions
axelpalecommented, Oct 11, 2018

Here are both for you @LinusU! I extended the empty-file test case with a Buffer.isBuffer(...) check. As predicted, this test fails without the explicit encoding argument. With it, all green 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Express req.body is empty - node.js - Stack Overflow
For the specific case you're talking about, you usually need only 'body-parser' module to be able to access the form input fields.
Read more >
req.body coming back as an empty object : r/node - Reddit
I am just trying to get data from my client code and POST it to my server code. Currently, I am able to...
Read more >
Express body-parser middleware
Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the req.body property. Note As req.body ......
Read more >
request.body is undefined in node js - You.com
Your problem is that Express doesn't use error first callbacks for its route handlers. The below code won't work because the app.post handler...
Read more >
Node Express Empty body when using python API POST ...
Okay, so i compared my pythons request against my web-app's request by printing the request to the console in node. I found that...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found