【问题标题】:Passing formData to Express middleware, Req.body is returning empty object将 formData 传递给 Express 中间件,Req.body 返回空对象
【发布时间】:2021-07-13 14:37:19
【问题描述】:

我正在尝试从客户端获取 formData,

<!-- begin snippet: js hide: false console: true babel: false -->
/**
 * @swagger
 * /post_image_question:
 *   post:
 *     description: Post an image question
 *     parameters:
*       - name: question
 *         description: Object of userId and questions array
 *         type: object
 *         in: formData
 *         properties:
 *           userId:
 *             type: string
 *           questions:
 *             type: array
 *             items:
 *               type: object
 *               properties:
 *                 question_title:
 *                   type: string
 *                 question_description:
 *                   type: string
 *                 text_question:
 *                   type: string
 *                 code_snippet:
 *                   type: string
 *                 tagged_technologies:
 *                   type: string
 *                 image_question:
 *                   type: string
 *       - name: image_question
 *         description: The question in form of image
 *         type: file
 *         in: formData
 *         consumes:
 *         - multipart/form-data
  *     responses:
 *       200:
 *         description: Success
 *       400:
 *         description:Bad Request
 *       404:
 *         description:Not Found
 *       500:
 *         description: Internal Server Error
 */

我正在将数据传递给中间件,我正在记录 req.body 并获取空对象,我可以做些什么来获取 formData 并将其转换为 json 数据

这是我的招摇文档

【问题讨论】:

  • 您需要提供minimal reproducible example。我们无法判断您的客户端代码为何无法发送数据或您的服务器端代码为何无法解析数据,甚至无法说明是哪种情况。

标签: javascript


【解决方案1】:

你需要在你的 index.js 中有app.use(express.json());

【讨论】:

  • 我只有 app.use(express.json()),如果我将中间件传递给 router.post(),我不会得到 formData,但如果我删除该中间件,我就会得到它来自 router.post()
  • FormData 对象不会被编码为 JSON,因此无济于事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2017-08-30
  • 2021-05-05
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多