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

问题描述 投票:0回答:1

我被困了最后两天。我已经尝试了所有的解决方案,但在 nodejs 中使用 PUT 和 PATCH 运行方法时,我仍然得到 undefined 或 {} object

邮递员屏幕截图在这里

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"
  },
node.js express rest patch put
1个回答
0
投票

您的 Postman 请求设置为

form-data
,这意味着
multipart/form-data
的内容类型并且您没有任何 Express 中间件来读取/解析该内容类型。

将邮递员更改为

x-www-form-urlencoded
json
以匹配您已有的中间件,否则您将必须安装可以处理
multipart/form-data
的中间件。通常,除非您将文件数据与表单数据一起上传,否则您不会使用
multipart/form-data
,因为这就是使用多部分(上传多个部分)的原因。

在 Postman 示例中,您显示了截图,

x-www-form-urlencoded
的内容类型应该可以正常工作,您的
app.use(bodyParser.urlencoded({ extended: true }))
中间件将处理它,这就是标准的 HTML 表单上传通常是什么。

© www.soinside.com 2019 - 2024. All rights reserved.