简体   繁体   English

请求正文未传递给 API

[英]Body of request not being passed to API

I'm trying to do a PUT request to an update controller from a react form (Mongoose API).我正在尝试从反应表单(Mongoose API)发出对更新 controller 的 PUT 请求。 Everything is passing over to the request, except the body.一切都传递给请求,除了正文。 Now, this is my first time using FormData, so I'm almost positive that is where the issue lies, but I can't seem to sort out where the problem is..现在,这是我第一次使用 FormData,所以我几乎可以肯定这就是问题所在,但我似乎无法找出问题所在..

The Submit action from the form表单中的提交操作

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})
      }
    })
  }

The Helper Method that set up the request设置请求的辅助方法

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)
  }
}

And the controller I've commented out the rest of the logic to remove the clutter while I TS this issue和 controller我已经注释掉了逻辑的 rest 以消除混乱,而我 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
}

UPDATE: I was able to get the FormData into an actual object using Object.fromEntries(user) - but it still won't pass into the request.. I have tried two ways:更新:我能够使用Object.fromEntries(user)将 FormData 转换为实际的 object - 但它仍然不会传递到请求中。我尝试了两种方法:

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)
  }
}

And

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)
  }
}

But req.body is still an empty object..但是 req.body 仍然是一个空的 object..

This has been solved, and it was all my flippin computer's fault..这已经解决了,这都是我的翻盖电脑的错..

On a whim, I killed node_modules and the package.lock files and reinstalled the deps.. and it started working.. My guess is that bodyParser didn't fully install..一时兴起,我杀死了 node_modules 和 package.lock 文件并重新安装了deps ..它开始工作了..我的猜测是bodyParser没有完全安装..

Thank you all for the help.谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM