简体   繁体   中英

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

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

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:

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..

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..

Thank you all for the help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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