如何使用Axios访问React功能组件向localhost服务器发出的get请求中的数据



我有一个MySQL数据库,其中包含一个客户列表。我可以使用以下代码通过Express从服务器端访问此列表:

app.get("/customer/lookup", (req, res) => {
const sqlSelect =
"SELECT * FROM customers;";
db.query(sqlSelect, (err, result) => {
if (!err) {
console.log(result);
} else {
console.log(err);
}
});
});

我可以看到我的终端中显示的JS对象数据,所以我知道我的查询是成功的。然而,我无法成功地从我的前端React组件发出GET请求。这是我正在使用的代码:

import React, {useState, useEffect} from "react";
import axios from "axios";
import { Link, Switch, Route } from 'react-router-dom';
function LookupTable() {
const [customerList, setCustomerList] = useState([]);
useEffect(()=> {
axios.get("http://localhost:4000/customer/lookup")
.then(response => {
setCustomerList(response.data)
});
}, []);
return (
<div>
<h1>Lookup Table</h1>
{customerList.map((val)=> {
return <p>Customer: {val.fullName}</p>
})}
</div>
);
}
export default LookupTable;

我现在只是想在浏览器中呈现相同的JS对象数据,但我只能呈现h1元素。我尝试在setCustomerList(response.data)之后的useEffect函数中控制台记录customerList,发现它是一个空对象。

我在这里错过了什么?

您实际上需要从服务器返回结果。目前您只将它们记录到控制台。

类似的东西

app.get("/customer/lookup", (req, res, next) => {
const sqlSelect = "SELECT * FROM customers;";
db.query(sqlSelect, (err, result) => {
if (!err) {
console.log(result);
res.json(result);
} else {
console.log(err);
next(err);
}
});
});

最新更新