【问题标题】:User.id is undefinedUser.id 未定义
【发布时间】:2019-07-12 20:47:50
【问题描述】:

我正在建立一个用户可以注册的网站,但是注册完成后什么也没有发生,它应该进入该网站。

我用 console.log 测试过,发现我的user.id 是未定义的。

这是我在服务器端的注册:

const handleRegister = (req, res, db, bcrypt) => {
    const { email, name, password } = req.body;
    if (!email || !name || !password) {
        return res.status(400).json('incorrect form submission');
    }
    const hash = bcrypt.hashSync(password);
    db.transaction(trx => {
        trx.insert({
            hash: hash,
            email: email
        })
        .into('login')
        .returning('email')
        .then(loginEmail => {
            console.log(email)
            return trx('users')
            .returning('*')
            .insert({
                email: email,
                name: name,
                joined: new Date()
            })
            .then(user => {
            res.json(user[0]);
            })
        })
        .then(trx.commit)
        .catch(trx.rollback)
    })

    .catch(err => res.status(400).json('unable to register ' + err))

}module.exports = {
handleRegister: handleRegister
};

这是我在前端的注册:

import React from 'react';

class Register extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            name: '',
            email: '',
            password: ''
        }
    }

    onNameChange = (event) => {
        this.setState({name: event.target.value})
    }

    onEmailChange = (event) => {
        this.setState({email: event.target.value})
    }

    onPasswordChange = (event) => {
        this.setState({password: event.target.value})
    }

    onSubmitSignIn = () => {
        fetch('http://localhost:3000/register', {
            method: 'post',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                name: this.state.name,
                email: this.state.email,
                password: this.state.password   
            })
        })
        .then(response => response.json())
        .then(user => {
         console.log(user.id);
         if (user.id) {
            console.log(user, user.id);
            this.props.loadUser(user)
            this.props.onRouteChange('home');
        }console.log(user.id);
      })
    }

我在前端设置了console.log,它从不进入if语句。 我该如何解决这个问题?

【问题讨论】:

  • 当你在做 res.json(user[0]) 时你能检查你的代码返回什么吗?
  • 在 res.json(user[0]) 行之前在服务器端尝试 console.logging;然后打印什么?
  • 服务器上的 console.log(user) 给了我这样的新用户的 ID [40]
  • 临时解决办法是进入登录页面而不是主页

标签: javascript node.js json reactjs


【解决方案1】:

如果您使用的是 mongodb,则 id 字段定义为 _id

【讨论】:

  • 我正在使用 MySQL
猜你喜欢
  • 2018-04-27
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 2010-10-21
相关资源
最近更新 更多