【发布时间】:2022-08-05 22:50:34
【问题描述】:
我正在尝试连接我的 React 和 mySQL 连接,并且我已经使用和不使用密码完成了它,并且密码似乎给了我一个查询是空的错误,但是当我打印 req.body 时,它有所有我的信息。我在查询之前打印 req.body,所以我不确定为什么它认为它是空的。
{ 姓名:\'123\',年龄:\'123\',地址:\'123\',租金:\'123\',
租赁长度:\'1\',开始日期:\'2022-06-01\'}code: \'ER_EMPTY_QUERY\', errno: 1065, sqlMessage: \'Query was empty\', sqlState: \'42000\', index: 0, sql: undefined这是 index.js(服务器)
const express = require(\'express\') const app = express() const mysql = require(\'mysql\') const cors = require(\'cors\') app.use(cors()) app.use(express.json()) const db = mysql.createConnection({ user: \'root\', host: \'localhost\', password: \'password\', database: \'tenantsystem\' }); app.post(\'/create\', (req, res) => { console.log(req.body) const name = req.body.name const age = req.body.age const address = req.body.address const rent = req.body.name const leaseLength = req.body.leaseLength const startDate = req.body.startDate db.query(\'INSERT INTO tenants (name, age, address, rent, lease_length, start_date) VALUES (?,?,?,?,?,?)\'[name, age, address, rent, leaseLength, startDate], (err, result) => { if (err) { console.log(err) } else { res.send(\"Values Inserted\") } }); }); app.listen(3001, () => { console.log(\"Server is running...\") })这是前端 App.js (react)
import \'./App.css\'; import { useState } from \'react\'; import Axios from \'axios\'; function App() { const [name, setName] = useState(\'\') const [age, setAge] = useState(\'\') const [address, setAddress] = useState(\'\') const [rent, setRent] = useState(\'\') const [leaseLength, setLeaseLength] = useState(\'\') const [startDate, setStartDate] = useState(\'\') const displayInfo = () => { console.log(name + age + address + rent + leaseLength + startDate) } const addTenant = () => { console.log(name) Axios.post(\'http://localhost:3001/create\', { name: name, age: age, address: address, rent: rent, leaseLength: leaseLength, startDate: startDate, }).then(() => { console.log(\'Success\'); }) } return ( <div className=\"App\"> <div className=\"information\"> <label>Name: </label> <input type=\"text\" onChange={(e) => { setName(e.target.value) }} /> <label>Age: </label> <input type=\"number\" onChange={(e) => { setAge(e.target.value) }} /> <label>Address: </label> <input type=\"text\" onChange={(e) => { setAddress(e.target.value) }} /> <label>Rent: </label> <input type=\"number\" onChange={(e) => { setRent(e.target.value) }} /> <label> lease length in months</label> <input type=\"number\" onChange={(e) => { setLeaseLength(e.target.value) }} /> <label>start date: </label> <input type=\"date\" onChange={(e) => { setStartDate(e.target.value) }} /> <button onClick={addTenant}> Add Tenant</button> </div> </div> ); } export default App;