无法将React的更新发布到MySQL数据库

时间:2019-06-25 10:33:01

标签: javascript mysql node.js reactjs

我从朋友那里得到一个项目,该项目使用React.js,Node.js,Express.js和MySQL技术。而且,当我处理CRUD部分时,我仅设法进行了输入更新,但是无法对数据库进行更改。

这是我的React代码:

import React, { Component } from "react";
import axios from "axios";
import { InputText } from "primereact/inputtext";
import { Button } from "primereact/button";

export class EditFK extends Component {
  constructor() {
    super();
    this.state = {
      id: "",
      nama: null,
      fakultas: []
    };
  }

  componentDidMount() {
    axios.get("http://localhost:3210/fakultas").then(getdata => {
      this.setState({
        fakultas: getdata.data
      });
    });
  }

  saveData() {
    axios
      .put(`http://localhost:3210/fakultas/edit/${this.params}`)
      .then(postdata => {
        this.setState({
          dataTableValue: postdata.data
        });
      });
  }

  render() {
    return (
      <div className="p-grid p-fluid">
        <div className="p-col-12 card card-w-title">
          <h1>Edit Fakultas</h1>
        </div>
        <div className="p-col-6">
          <div className="card card-w-title">
            <h4>Ubah Fakultas</h4>
            <div className="p-grid">
              <div className="p-col-12 p-md-6">
                <InputText placeholder="Nama" type="text" />
              </div>
            </div>
          </div>
        </div>
        <div className="p-col-12">
          <div className="p-col-3">
            <Button
              label="Update"
              icon="pi pi-pencil"
              onClick={this.saveData()}
            />
          </div>
        </div>
      </div>
    );
  }
}

这是我的后端代码:

//get fakultas by id
app.get("/fakultas/:id", (req, res) => {
  var sql = `SELECT * FROM fakultas WHERE id = ${req.params.id}`;
  db.query(sql, (err, result) => {
    if (err) {
      throw err;
    } else {
      res.send(result);
    }
  });
});

//edit fakultas by id
app.put("/fakultas/edit/:id", (req, res) => {
  console.log(req.body);
  var data = {
    id: req.body.id,
    nama: req.body.nama
  };
  var sql = `UPDATE fakultas set ? WHERE id = ${req.params.id}`;
  db.query(sql, data, (err, result) => {
    if (err) {
      throw err;
    } else {
      res.send({
        status: `Data Berhasil di Update`,
        id: req.body.id,
        nama: req.body.nama
      });
    }
  });
});

下面的链接是fakultas表中的列:

fakultas table column screenshot

1 个答案:

答案 0 :(得分:0)

我真的很了解sql查询的基础知识,但是我认为您应该将问号替换为要设置的列的名称:

  var sql = `UPDATE fakultas set columnName = newValue WHERE id = ${req.params.id}`;

加上:我为您找到了this,我认为用户发布的代码就是您所需要的