首页 > 解决方案 > NodeJS PUT 请求返回错误 400(错误请求)

问题描述

我正在尝试使用 NodeJS、Express 和 MongoDB 执行 PUT 请求。我目前遇到的问题是我一直收到一个error **400**,我不确定为什么。

我真正想做的是在某个用户注册后上传编辑我的用户集合中的一个字段。这应该发生在特定的路线上。/user/edit/:id

我的应用程序采用标准 MVC 模式构建。

这是我Mongo Schema的结构:

let UserSchema = new mongoose.Schema({
  username: String,
  password: String,
  email: String,
  avatar: String,
  firstName: String,
  lastName: String,
  laps:[{ type: Schema.Types.ObjectId, ref: 'Stats' }]
});

这是我的服务:

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

我正在使用的控制器:

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

路由器文件中的路由路径:

router.post('/edit/:id', UserController.updateUser);

服务器文件中用户的路由路径:

app.use('/user', require('./api/routes/user.route'));

我知道大多数4**错误来自应用程序的前端,因此我还将发布我的表单和它背后的构造函数。我使用 ReactJS 作为框架。

前端形式:

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 (
      <div className="container-fluid no-gutters page-login">
        <div className="row">
          <div className="login-wrapper">
            <h2> Edit User Profile </h2>

            <form onSubmit={this.resultsSubmit}>
              <div className="form-group">
                Paste Avatar URL: <input type="text" value={avatar} name="avatar" id="" onChange={this.formChange} />
              </div>
              <input type="submit" className="btn btn-primary btn-lg btn-block" value="submit"/>
            </form>

          </div>
        </div>
      </div>
    )
  }
}
function mapStateToProps(state) {
  const { layout } = state;
  return {
    layout
  };
}
export default connect(mapStateToProps)(UserProfile);

我的派遣:

function addAvatar(avatar, token) {
  return dispatch => {
    dispatch(request());
    userService.addAvatar(avatar, token)
      .then(
        user => {
          dispatch(success(user));
          history.push(`${process.env.PUBLIC_URL}/`);
        },
        error => {
          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 } }
}

HTTP Post 服务:

function addAvatar(avatar){
  const requestOptions = {
    method: 'POST',
    headers: authHeader(),
    body:  avatar
  };
  return fetch('http://localhost:3003/user/edit/:id', requestOptions)
    .then(response => {
      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 => console.log(data,"WHT DO WE HAVE HERE?"));
}

为巨大的代码墙道歉,但我想包括所有的位。

我在路由 POST 上收到错误 400(错误请求) http://localhost:3003/user/edit/:id

标签: node.jsreactjsexpress

解决方案


在您的获取请求中,您只发送头像作为正文,在您的 updateUser 函数中,您有以下 if 语句:

if (!req.body._id){
    return res.status(400).json({status: 400, message: "Id must be present"})
}

所以显然你的身体请求中没有 _id 而是一个头像,实际上你将你的 id 作为参数发送

'http://localhost:3003/user/edit/:id'

因此,您可以将此行更改为解决方法

if (!req.params.id){

希望能帮助到你。


推荐阅读