【问题标题】:unable to get request body in postman无法在邮递员中获取请求正文
【发布时间】:2019-11-14 13:15:10
【问题描述】:

我有一个控制器函数和一个端点:

控制器

uploadSalesOrderFromExcel : async function (req,res) {
        console.log(req.body);
        if (!req.body.branchId) {
            return res.status(400).send({ Error: "Branch Id is required." });
          }
          if (!req.file) {
            return res.status(400).send({ Error: "Excel file is required." });
          }
          const excelData = await readExcel(file, { sheet: 'Sales Order' })
          res.send(excelData);
        }

路线 http://localhost:8080/sp/salesOrders/uploadSalesOrder

现在从邮递员那里点击 API 后,我得到了这个响应:

{
    "Error": "Branch Id is required."
}

cURL

curl -X POST \
  http://localhost:8080/sp/salesOrders/uploadSalesOrder \
  -H 'Accept: */*' \
  -H 'Accept-Encoding: gzip, deflate' \
  -H 'Authorization: Basic Mzo5MTQ4MDk0ZjIxMDJhM2Q3M2U0OWY5NDljMGQ2YTIzYw==' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Length: 164' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Host: localhost:8080' \
  -H 'Postman-Token: 6bd29ccf-ebad-4299-8687-9ea46cf35686,4ea8d417-df27-49a1-8d84-3aabddbccd2c' \
  -H 'User-Agent: PostmanRuntime/7.19.0' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F branchId=5

【问题讨论】:

  • 你有身体解析器设置吗? Express 默认不解析请求体,见body-parser
  • 你能在req.body中发布你得到的东西吗
  • {} 仅限@Shubh。
  • 那我猜你缺少`body parser`来解析即将到来的数据。请发布你的app.jsindex.js
  • 但之前制作的 API 运行良好。我们有body-parser。 @Shubh,当我将它从 raw 传递为 content-type:application/json 时,它工作正常。

标签: node.js express post postman


【解决方案1】:

我认为您应该改用 -d 标志并将 branchId 作为对象传递。试试

  curl -X POST \
  http://localhost:8080/sp/salesOrders/uploadSalesOrder \
  -H 'Accept: */*' \
  -H 'Accept-Encoding: gzip, deflate' \
  -H 'Authorization: Basic Mzo5MTQ4MDk0ZjIxMDJhM2Q3M2U0OWY5NDljMGQ2YTIzYw==' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Length: 164' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Host: localhost:8080' \
  -H 'Postman-Token: 6bd29ccf-ebad-4299-8687-9ea46cf35686,4ea8d417-df27-49a1-8d84-3aabddbccd2c' \
  -H 'User-Agent: PostmanRuntime/7.19.0' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -d '{"branchId": 5}'

【讨论】:

  • 这无论如何都行不通,因为内容类型与正文格式 (JSON) 不匹配
【解决方案2】:

我没有使用过multer。这就是我在请求正文中得到空白对象的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 2017-12-29
    • 2020-03-11
    • 2020-12-11
    • 1970-01-01
    • 2021-07-19
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多