Search code examples
node.jsexpressrestpatchput

PUT/PATCH merhtod return Undefind and {} object , when use the with form-data in nodejs,expressJs


I'm stuck for the last two days. I have tried all the solutions for it but still, I'm getting undefined or {} object when running the method with PUT and PATCH in nodejs

Postman screen shot is here

index.js

[const express = require("express")
const cors = require("cors")
const bodyParser = require("body-parser")
require("./db/db.config")

const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

const PORT = 8000

const Customer = require("./routes/customerRoutes")
app.use(cors())
app.use(Customer)

app.listen(PORT, () => {
  console.log("Server is running on", PORT)
})][1]

package.json

  "dependencies": {
    "body-parser": "^1.20.1",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "moment": "^2.29.4",
    "mongoose": "^6.9.2",
    "multer": "*",
    "validator": "^13.9.0"
  },

Solution

  • Your Postman request is set to form-data which means a content-type of multipart/form-data and you don't have any Express middleware to read/parse that content-type.

    Change postman to either x-www-form-urlencoded or json to match the middleware you do have or you will have to install middleware that can handle multipart/form-data. Usually, you would not use multipart/form-data unless you were uploading file data along with your form data since that's why multi-part is used (multiple parts to the upload).

    In the Postman example you show a screenshot of, the content-type of x-www-form-urlencoded should work just fine and your app.use(bodyParser.urlencoded({ extended: true })) middleware will handle it and that's what a standard HTML form upload would typically be.