【问题标题】:NodeJS PUT request returns error 400 (Bad Request)NodeJS PUT 请求返回错误 400(错误请求)
【发布时间】:2019-07-28 10:32:57
【问题描述】:

我正在尝试使用 NodeJS、Express 和 MongoDB 执行 PUT 请求。我目前遇到的问题是我不断收到error **400**,但我不确定具体原因。

我真正想做的是在某个用户注册后上传编辑我的USER集合中的field。这应该发生在特定的/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

【问题讨论】:

  • 您在开发者工具的网络选项卡中遇到什么错误?这可能是 CORS 问题。
  • 我认为这可能是因为 id 字段在您正在创建的用户 JSON 对象中没有键。您可以尝试将其更改为id: id 看看是否有帮助?

标签: node.js reactjs express


【解决方案1】:

在您的获取请求中,您只发送头像作为正文,在您的 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){

希望对你有帮助。

【讨论】:

  • 是的,但我从某处收到 null 作为输入
【解决方案2】:

下面的 sn-p 表明你正在尝试从请求正文中获取 ID 参数。

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

,路由 /user/edit/:id 表明 ID 参数实际上是通过 URL 传递的,要访问它,您只需使用 req.params.id 从 URL 中获取您的 ID . req.params 包含通过路由或 URL 路径传递的所有参数。

上面的sn-p应该改成;

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

查看https://expressjs.com/en/guide/routing.html#route-parameters 获取有关如何处理路由参数的正确指南。

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多