【问题标题】:All 'req.body' values ​are string - Express and multer所有 'req.body' 值都是字符串 - Express 和 multer
【发布时间】:2022-01-10 13:01:48
【问题描述】:

我在获取“字符串”以外的值时遇到问题,我有一个表格可以将照片上传到 cloudinary。收到请求数据的时候,都是'string'类型的,也就是object或者array类型的值,我转换一下,例如:

{ name: "name of user" } to [object Object] , true to "true" and ["user1", "user2"] to "user1,user2"

在客户端,我有一个从表单接收数据的函数,并使用 axios 向服务器发出请求:

// Request

async function updateUser(formValues) {
  try {
    // Create Form Data
    const formData = new FormData();

    // Form fields
    const fields = Object.keys(formValues);

    for (const field of fields) {
      formData.append(field, formValues[field]);
    }

    const res = await axios({
      method: "PUT",
      url: `mypage/api/updateUser`,
      data: formData,
    });

  } catch (err) {
   //
  }
}

export default updateUser;

在服务器端,我配置了multer和express如下:

'use strict'

const multer = require('multer')
const express, { Router } = require('express')
const app = express()
const router = Router()

// Middlewares
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// MULTER CONFIG
const diskStorage = multer.diskStorage({
  filename: (_, file, cb) => cb(null, file.originalname)
})

const upload = multer({ storage: diskStorage })

// EXAMPLE
router.post(
  '/api/updateUser',
  upload.single('profilePhoto'),
  function(req, res) {
  /* 
    req.body is equal to {
      name: "User",
      isPremium: true,
      user: { name: "username" },
      favoritesGames: ["World of Warcraft", "Age of Empires"]
    }
  */
  console.log(req.body.user)
  // return "[object Object]"
  
  console.log(req.body.isPremium)
  // return "true"
  
  console.log(req.body.favoritesGames)
  // return "World of Warcraft, Age of Empires"
  
  // I need to get the body data as it arrives 
)

// SET PORT
const port = process.env.PORT

// INIT APP
app.listen(port || 4000, function() {
  console.log('[INFO]', `The server is running on ${process.env.PUBLIC_URL}`)
})

我需要数据,因为它来自客户端,内容类型是multipart/form-data,它不是application/json,所以我认为它不能读取'string'以外的数据。有什么解决办法吗?

【问题讨论】:

    标签: express multer


    【解决方案1】:

    我为这个问题找到了一个很好的解决方案。实际上,从前端,您必须发送包装在 JSON.stringify 中的值,然后问题就解决了。

    例子:

    async function updateUser(values) {
      try {
        // Create Form Data
        const formData = new FormData();
    
        // Get fields of Form
        const fields = Object.keys(values);
        
        // Types to stringify
        const typesToStringify = ["object", "boolean", "array"]
    
        for (const field of fields) {
          for (type of typesToStringify) {
            if (typeof formValues[field] === type) {
              formData.append(field, JSON.stringify(values[field]));
            } else {
              formData.append(field, values[field]);
            }
          }       
        }
    
        // Request to api
      } catch (err) {
        //
      }
    }

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 1970-01-01
      • 2017-11-24
      • 2017-01-28
      • 2014-04-09
      • 2013-05-12
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多