【发布时间】:2021-04-06 13:36:33
【问题描述】:
我需要根据来自客户端的一个或多个输入来查询 MySQL 数据库。为了测试此功能,我尝试仅基于一个输入在我的 GET 请求中进行查询。
对于初学者,这是我的功能性 React 组件中的代码:
import React, {useState, useEffect} from "react";
import axios from "axios";
function LookupResult(props) {
const [customerList, setCustomerList] = useState([]);
useEffect(()=> {
axios.get("http://localhost:4000/customer/lookup", {
name: "Timmy Test"
})
.then(response => {
setCustomerList(response.data)
console.log(customerList)
});
}, []);
return (
<div>
<h1>Lookup Table</h1>
{customerList.map(customer => (
<p key={customer.id}>
{customer.full_name}
</p>
))}
</div>
);
}
export default LookupResult;
一旦我可以在服务器端访问该名称参数,我最终将用父组件中的道具替换 name: "Timmy Test" 中的“Timmy Test”。
在服务器端,这是我当前的代码:
app.get("/customer/lookup", (req, res) => {
const name = "Timmy Test";
const sqlSelect =
"SELECT * FROM customers WHERE full_name = ?";
db.query(sqlSelect, [name], (err, result) => {
if (!err) {
res.json(result);
// console.log(result);
} else {
console.log(err);
}
});
});
我的目标是用来自 React 组件的相同 prop/参数替换 get 请求中的“Timmy Test”。
那么,我如何将该参数从我的 React 组件中的 axios.get 请求传递到我的服务器端代码中的 app.get 请求?
我解决这个问题的方法是否正确,还是有更好的方法?请记住,我最终需要使用多个可能的输入之一来查询我的 SQL 数据库,有时还需要不止一个输入。
【问题讨论】: