最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

未定义的值通过React和Node.js传递到MySQL数据库

网站源码admin22浏览0评论

未定义的值通过React和Node.js传递到MySQL数据库

未定义的值通过React和Node.js传递到MySQL数据库

我在React的前端一直通过未定义的值传递给Node中的后端服务器。我正在尝试创建一个注册容器,该容器将在数据库中创建一个帐户。

这是我的点击功能:

register(event) {
        event.preventDefault();

        let newUser = {
          name : this.state.name,
          password : this.state.password,
          email : this.state.email
        }
        Axios.post('http://localhost:2999/Join', newUser).then((response) => {
            console.log(response.data);

            if (response.data.success) {
                console.log("Successful Register");
                this.props.close();
            } else {
                console.log("Failed to Register");
                console.log(response.data.error);
            }
        });
    }

我目前已进行设置,其中通过onChange函数更新表单中每个框的状态:

handleNameChange(event) {
        this.setState({name : event.target.value});
    }

    handlePwChange(event) {
      this.setState({password : event.target.value});
    }

    handleEmailChange(event) {
      this.setState({email : event.target.value});
    }

这是我的Server.js中的POST函数:

app.post('/Join', (req, res) => {
    const name = req.params.name;
    console.log(name);
    const password = req.params.password;
    console.log(password);
    const email = req.params.email;
    console.log(email);
    const REGISTER_USER_QUERY = `INSERT INTO users (name, password, email) VALUES ('${name}', '${password}', '${email}');`;
    connection.query(REGISTER_USER_QUERY, (err, results) => {
        if (err) {
            return res.send(err);
        } else {
            return res.send('Successfully registered player');
        }
    });
});
回答如下:

您应使用req.body中的数据。因此,在您的代码中只需更改:

app.post('/Join', (req, res) => {
    const name = req.body.name;
    console.log(name);
    const password = req.body.password;
    console.log(password);
    const email = req.body.email;
    console.log(email);
    const REGISTER_USER_QUERY = `INSERT INTO users (name, password, email) VALUES ('${name}', '${password}', '${email}');`;
        connection.query(REGISTER_USER_QUERY, (err, results) => {
        if (err) {
           return res.send(err);
        } else {
           return res.send('Successfully registered player');
      }
  });
});

从URL传递参数时,您应使用req.params。假设您要从ID为1000的用户获取数据。

您的路线将是:

app.get('/user/:id', (req, res) => {
    const id = req.params.id
    res.json({userid: id})
})

在上面的示例中,如果您在路线http://localhost:3000/user/1000中进行请求

我们有回应:

{userid: 1000}
发布评论

评论列表(0)

  1. 暂无评论