【问题标题】:Body of request not being passed to API请求正文未传递给 API
【发布时间】:2021-07-15 06:14:04
【问题描述】:

我正在尝试从反应表单(Mongoose API)向更新控制器发出 PUT 请求。一切都传递给请求,除了正文。现在,这是我第一次使用 FormData,所以我几乎可以肯定这就是问题所在,但我似乎无法找出问题所在..

表单中的提交操作

const clickSubmit = () => {
    // console.log('Values on submit before FormData: ', values) // Shows the state object as expected
    let userData = new FormData()
    values.name && userData.append('name', values.name)
    values.email && userData.append('email', values.email)
    values.password && userData.append('password', values.password)
    values.about && userData.append('about', values.about)
    values.photo && userData.append('photo', values.photo)
    update({
      userId: match.params.userId
    }, {
      t: jwt.token
    }, userData).then((data) => {
      if (data && data.error) {
        setValues({...values, error: data.error})
      } else {
        setValues({...values, 'redirectToProfile': true})
      }
    })
  }

设置请求的辅助方法

const update = async (params, credentials, user) => {
  console.log('The params: ', params)  // passes the user ID just fine
  console.log('The credentials:', credentials) // passes the JWT just fine
  console.log('The user object: ', ...user) // has all the information I'm updating, albeit in an array form that I can't really work with
  try {
    let response = await fetch('/api/users/' + params.userId, {
      method: 'PUT',
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + credentials.t
      },
      body: user
    })
    return await response.json()
  } catch (err) {
      console.log(err)
  }
}

和控制器我已经注释掉了其余的逻辑以消除混乱,同时我 TS 这个问题

const update = async (req, res) => {
  console.log(req)
  const user = await User.findById(req.params.userId)
  console.log('user after find: ', user) // returns the user that I want to modify from the database
  console.log('body of request: ', req.body) // empty object
}

更新: 我能够使用 Object.fromEntries(user) 将 FormData 转换为实际对象 - 但它仍然不会传递到请求中。我尝试了两种方法:

const update = async (params, credentials, user) => {
  console.log('The params: ', params)
  console.log('The credentials:', credentials)
  console.log('The user object: ', ...user)
  let infoToUpdate = Object.fromEntries(user)
  console.log('infoToUpdate: ', infoToUpdate);


  try {
    let response = await fetch('/api/users/' + params.userId, {
      method: 'PUT',
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + credentials.t
      },
      body: {
       "name": infoToUpdate.name,
       "email": infoToUpdate.email,
       "about": infoToUpdate.about
      }
    })
    return await response.json()
  } catch (err) {
      console.log(err)
  }
}

const update = async (params, credentials, user) => {
  console.log('The params: ', params)
  console.log('The credentials:', credentials)
  console.log('The user object: ', ...user)
  let infoToUpdate = Object.fromEntries(user)
  console.log('infoToUpdate: ', infoToUpdate);


  try {
    let response = await fetch('/api/users/' + params.userId, {
      method: 'PUT',
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + credentials.t
      },
      body: infoToUpdate
    })
    return await response.json()
  } catch (err) {
      console.log(err)
  }
}

但是 req.body 仍然是一个空对象..

【问题讨论】:

  • 您需要在服务器端处理multipart/form-data 请求有效负载。 multer 是一个受欢迎的选择
  • 确保您使用的是适当的中间件。在您更新的示例中,您根本不再传递 formdata,因此 app.use(bodyParser.json()) 应该足以将您的数据输入控制器。
  • 请注意,如果 user.photoFile(或类似的 Blob),则不能将其上传为 JSON。此外,如果您确实想要发送 JSON 有效负载,则应使用 body: JSON.stringify(infoToUpdate)

标签: javascript reactjs forms rest mongoose


【解决方案1】:

这已经解决了,都是我的翻盖电脑的错..

一时兴起,我杀死了 node_modules 和 package.lock 文件并重新安装了 deps.. 它开始工作.. 我的猜测是 bodyParser 没有完全安装..

感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多