title: NodeJS PUT request returns error 400 (Bad Request)
body: <p>I am trying to do a PUT request with NodeJS, Express and MongoDB. The issue that I am currently having is that I keep receiving an <code>error **400**</code> and I am not sure exactly why. </p>
  
  <p>What I am exactly trying to do is upload edit a <strong>field</strong> in my <strong>USER</strong> collection, after a certain user has been registered. This is supposed to happen on a specific <code>/user/edit/:id</code> route. </p>
  
  <p>My application is structured with a standard MVC pattern.</p>
  
  <p>Here is how my <code>Mongo Schema</code> is structured:</p>
  
  <pre><code>let UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    email: String,
    avatar: String,
    firstName: String,
    lastName: String,
    laps:[{ type: Schema.Types.ObjectId, ref: 'Stats' }]
  });
  </code></pre>
  
  <p>This is my service:</p>
  
  <pre><code>exports.updateUser = async function(user) {
    let id = user.id;
    let oldUser;
    try {
      //Find the old User Object by the Id
      oldUser = await User.findById(id);
    } catch(e) {
      throw Error("Error occured while Finding the User");
    }
    // If no old User Object exists return false
    if (!oldUser) {
      return false;
    }
    //Edit the User Object
    oldUser.firstName = user.firstName || oldUser.firstName;
    oldUser.lastName = user.lastName || oldUser.lastName;
    oldUser.avatar = user.avatar || oldUser.avatar;
    try {
      let savedUser = await oldUser.save();
      return savedUser;
    } catch(e) {
      throw Error("And Error occured while updating the User");
    }
  };
  </code></pre>
  
  <p>The Controller that I am using:</p>
  
  <pre><code>exports.updateUser = async function(req, res, next) {
    if (!req.body._id){
      return res.status(400).json({status: 400, message: "Id must be present"})
    }
    let id = req.body._id;
    let user = {
      id,
      firstName: req.body.firstName || null,
      lastName: req.body.lastName || null,
      avatar: req.body.avatar || null
    };
    try {
      let updatedUser = await UserService.updateUser(user);
      return res.status(200).json({status: 200, data: updatedUser, message: "Successfully Updated User"})
    } catch(e) {
      return res.status(400).json({status: 400, message: e.message})
    }
  };
  </code></pre>
  
  <p>Route path in router file:</p>
  
  <pre><code>router.post('/edit/:id', UserController.updateUser);
  </code></pre>
  
  <p>Route path for users inside server file:</p>
  
  <pre><code>app.use('/user', require('./api/routes/user.route'));
  </code></pre>
  
  <p>I know that most <code>4**</code> errors come from the front end of the application, so I will also post my form and the constructor behind it. I am using ReactJS as a framework. </p>
  
  <p>Front end Form:</p>
  
  <pre><code>class UserProfile extends Component {
    constructor(props) {
      super(props);
      this.state = {
        avatar: '',
        resultsSubmitted: false
      };
      this.formChange = this.formChange.bind(this);
      this.resultsSubmit = this.resultsSubmit.bind(this);
    }
    formChange(e) {
      console.log("form changed" + e.target);
      const { name, value } = e.target;
      this.setState({ [name]: value });
    }
    resultsSubmit(e) {
      e.preventDefault();
      const accessToken = JSON.parse(localStorage.getItem('auth_user')).data.access_token;
      const { avatar } = this.state;
      const { dispatch } = this.props;
      if (avatar) {
        console.log("submitting results: " + avatar);
        dispatch(userActions.addAvatar(avatar, accessToken));
      }
    }
    render(){
        const { avatar, resultsSubmitted} = this.state;
      return (
        &lt;div className="container-fluid no-gutters page-login"&gt;
          &lt;div className="row"&gt;
            &lt;div className="login-wrapper"&gt;
              &lt;h2&gt; Edit User Profile &lt;/h2&gt;
  
              &lt;form onSubmit={this.resultsSubmit}&gt;
                &lt;div className="form-group"&gt;
                  Paste Avatar URL: &lt;input type="text" value={avatar} name="avatar" id="" onChange={this.formChange} /&gt;
                &lt;/div&gt;
                &lt;input type="submit" className="btn btn-primary btn-lg btn-block" value="submit"/&gt;
              &lt;/form&gt;
  
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      )
    }
  }
  function mapStateToProps(state) {
    const { layout } = state;
    return {
      layout
    };
  }
  export default connect(mapStateToProps)(UserProfile);
  </code></pre>
  
  <p>My dispatch:</p>
  
  <pre><code>function addAvatar(avatar, token) {
    return dispatch =&gt; {
      dispatch(request());
      userService.addAvatar(avatar, token)
        .then(
          user =&gt; {
            dispatch(success(user));
            history.push(`${process.env.PUBLIC_URL}/`);
          },
          error =&gt; {
            dispatch(failure(error));
            dispatch(alertActions.error(error));
          }
        );
    };
    function request() { return { type: userConstants.AVATAR_REQUEST } }
    function success(user) { return { type: userConstants.AVATAR_SUCCESS, user } }
    function failure(error) { return { type: userConstants.AVATAR_FAILURE, error } }
  }
  </code></pre>
  
  <p>HTTP Post service:</p>
  
  <pre><code>function addAvatar(avatar){
    const requestOptions = {
      method: 'POST',
      headers: authHeader(),
      body:  avatar
    };
    return fetch('http://localhost:3003/user/edit/:id', requestOptions)
      .then(response =&gt; {
        if (!response.ok) {
          console.log("+",response,"+");
          return Promise.reject(response.statusText);
        }else{
          console.log(response, "the user service response was gooooooooooood");
        }
        return response.json();
      })
      .then(data =&gt; console.log(data,"WHT DO WE HAVE HERE?"));
  }
  </code></pre>
  
  <p>Apologies for the huge code wall but I wanted to include all the bits.</p>
  
  <blockquote>
    <p>I am getting an error 400 (Bad Request) on the route POST
    <code>http://localhost:3003/user/edit/:id</code></p>
  </blockquote>