无法注册新用户

时间:2019-05-24 10:47:31

标签: node.js reactjs axios

我在node.js中写的后端,在React.js中写的前端 我想向我的系统注册一个新用户。 如果我使用Postman,可以注册,但是不能在后端注册。

Register.js(react.js):

axios.defaults.baseURL = 'http://localhost:5040';

axios.post('/users/register', newUser)
  .then(res => console.log(res.data))
  .catch(err => console.log(err.response.data));

newUser = {name: "test", email: "test0991@gmail.ru", password: "123456", password2: "123456"}

后端:

router.post('/register', (req, res) => {
  const { errors, isValid } = validateRegisterInput(req.body);

  // Check Validation
  if(!isValid){
    return res.status(400).json(errors);
  }

  User.findOne({ email: req.body.email })
    .then(user => {
      if(user){
        *
      } else {
        *
        *
        *
        );

        const newUser = new User({
          *
          *
          *
          *
        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) =>{
            if(err) throw err;
            newUser.password = hash;
            newUser.save()
              .then(user => res.json(user))
              .catch(err => console.log(err));
          });
        });
      }
    });
});

错误:

Unhandled Rejection (TypeError): Cannot read property 'data' of undefined

console.log(newUser);
axios.post('/users/register', newUser)
  .then(res => console.log(res.data))
  .catch(err => console.log(err.res.data));

1 个答案:

答案 0 :(得分:0)

也许您没有发送数据。由于某些原因,您在调用newUser时会使用axios.post(),但是直到调用newUser之后才给axios.post()赋值。订单应该互换,像这样:

axios.defaults.baseURL = 'http://localhost:5040';

newUser = {name: "test", email: "test0991@gmail.ru", password: "123456", password2: "123456"}

axios.post('/users/register', newUser)
  .then(res => console.log(res.data))
  .catch(err => console.log(err.response.data));