首页 > 解决方案 > ER_TRUNCATED_WRONG_VALUE,在没有重新加载 MYSQL 的情况下发出 post 请求后 ID 未定义

问题描述

因此,我制作了一个简单的 CRUD 应用程序,并且在大多数情况下,除了一个小错误之外,它可以正常工作。在我提出发布请求并立即尝试编辑或删除它之后。它不起作用。我得到:代码:'ER_TRUNCATED_WRONG_VALUE',errno:1292,sqlMessage:“截断不正确的 DOUBLE 值:'undefined'”,sqlState:'22007',索引:0,sql:“DELETE FROM employees WHERE id = 'undefined';”

所以我知道在发出该发布请求并且不刷新之后,它没有 id,因此更新和删除方法不起作用。我尝试在帖子 AJAX 请求 ID 中设置它: res.data.id 但响应没有该数据,因此它不起作用。我已经坚持了一段时间。

应用程序.js:

import React, { useState, useRef } from 'react';
import axios from 'axios';
import './App.css';

function App() {

  const [name, setName] = useState('');
  const [age, setAge] = useState(0);
  const [country, setCountry] = useState('');
  const [position, setPosition] = useState('');
  const [wage, setWage] = useState(0);
  const [employeeList, setEmployeeList] = useState([]);
  const [newWage, setNewWage] = useState(0);

  const nameInputRef = useRef(null);
  const ageInputRef = useRef(null);
  const countryInputRef = useRef(null);
  const positionInputRef = useRef(null);
  const wageInputRef = useRef(null);
  const newWageInputRef = useRef(null);


  const getEmployees = () => {
    axios.get(`http://localhost:3001/employees`)
    .then(res => {
      setEmployeeList(res.data);
      console.log(res.data)
    })
    .catch(err => {
      console.error(err); 
    })
  };

  const addEmployee = () => {
    axios.post('http://localhost:3001/create', { 
      name, age, country, position, wage 
    })
    .then(() => {
      setEmployeeList([...employeeList, {
        name, age, country, position, wage
      }])
    })
    .catch(err => {
      console.error(err); 
    })
    nameInputRef.current.value = '';
    ageInputRef.current.value = '';
    countryInputRef.current.value = '';
    positionInputRef.current.value = '';
    wageInputRef.current.value = '';
  };

  const updateEmployeeWage = id => {
    axios.put(`http://localhost:3001/update`, {
      wage: newWage,
      id,
    })
    .then(() => {
      setEmployeeList(employeeList.map((val) => {
        return val.id === id ? {id: val.id, name: val.name, country: val.country, age: val.age, position: val.position, wage: newWage} : val
      }))
    })
    .catch(err => {
      console.error(err); 
    })
    newWageInputRef.current.value = '';
  };

  const deleteEmployee = id => {
    axios.delete(`http://localhost:3001/delete/${id}`)
    .then(() => {
      setEmployeeList(employeeList.filter((val) => {
        return val.id !== id
      }))
    })
    .catch(err => {
      console.error(err); 
    })
  };

  return (
    <div className="App">

      <div className="information">
        <label>Name:</label>
        <input
         type="text" 
         onChange={(e) => setName(e.target.value)}
         ref={nameInputRef}
         />

        <label>Age:</label>
        <input 
        type="number"
        onChange={(e) => setAge(e.target.value)}
        ref={ageInputRef}
        />

        <label>Country:</label>
        <input 
        type="text"
        onChange={(e) => setCountry(e.target.value)}
        ref={countryInputRef}
        />

        <label>Position:</label>
        <input
        type="text"
        onChange={(e) => setPosition(e.target.value)}
        ref={positionInputRef}
        />

        <label>Wage (year):</label>
        <input 
        type="number"
        onChange={(e) => setWage(e.target.value)}
        ref={wageInputRef}
         />

        <button 
        onClick={() => addEmployee()}
        >
          Add Employee
        </button>
      </div>

      <br />

      <div className="employees">
        <button
         onClick={() => getEmployees()}
        >
          Show Employees
        </button>

        {employeeList.map((val) => (
            <div className="employee" key={val.id}>

              <div>
                <h3>Name: {val.name}</h3>
                <h3>Age: {val.age}</h3>
                <h3>Country: {val.country}</h3>
                <h3>Position: {val.position}</h3>
                <h3>Wage: {val.wage}</h3>
              </div>

              <div>
                <input type="text"
                placeholder="Update wage.."
                onChange={(e) => setNewWage(e.target.value)}
                ref={newWageInputRef}
                />
                <button 
                onClick={() => updateEmployeeWage(val.id)}
                >
                  Update
                </button>

                <button 
                onClick={() => deleteEmployee(val.id)}
                >
                  Delete
                </button>
              </div> 

            </div>
        ))}
      </div>
    </div>
  );
}

export default App;

index.js

const express = require('express');
const mysql = require('mysql');
const cors = require('cors');

const app = express();

const PORT = 3001;

app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'employeeSystem'
});

app.get('/employees', (req, res) => {
  db.query(`SELECT * FROM employees`, (err, result) => {
      if (err) {
          console.log(err);
      } else {
          res.send(result);
      }
  })
});

app.post('/create', (req, res) => {   
  const name = req.body.name;
  const age = req.body.age;
  const country = req.body.country;
  const position = req.body.position;
  const wage = req.body.wage;

  db.query(`INSERT INTO employees (name, age, country, position, wage) VALUES (?,?,?,?,?);`, [name, age, country, position, wage], (err, result) => {
      if (err) {
          console.log(err);
      } else {
          res.send('Values Inserted');
      }
  })
});

app.put('/update', (req, res) => {
    const id = req.body.id;
    const wage = req.body.wage;
    db.query(`UPDATE employees SET wage = ? WHERE id = ?;`,[wage, id], (err, result) => {
        if (err) {
            console.log(err);
        } else {
            res.send(result);
        }
    })
});

app.delete('/delete/:id', (req, res) => {
    const id = req.params.id;
    db.query(`DELETE FROM employees WHERE id = ?;`, id, (err, result) => {
        if (err) {
            console.log(err);
        } else {
            res.send(result);
        }
    })
});  

app.listen(PORT, () => console.log(`App listening on port ${PORT}!`));

示例 api 输出:[{"id":15,"name":"John Doe","age":23,"country":"USA","position":"Full-Stack Developer","wage": 100000},{"id":16,"name":"Jeff Bezos","age":54,"country":"USA","position":"CEO","wage":999999999},{" id":27,"name":"Joe Rogan","age":53,"country":"USA","position":"UFC Commentator","wage":3000000}]

标签: javascriptmysqlreactjscrud

解决方案


推荐阅读