如何使用 Axios 从 React 功能组件向本地主机服务器发出的获取请求访问数据?
How to access data from get request made by a React functional component to localhost server using Axios?
我有一个包含客户列表的 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,但我发现它是一个空对象。
我在这里错过了什么?
您实际上需要 return 来自您服务器的结果。目前您只能将它们记录到控制台。
类似
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);
}
});
});
我有一个包含客户列表的 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,但我发现它是一个空对象。
我在这里错过了什么?
您实际上需要 return 来自您服务器的结果。目前您只能将它们记录到控制台。
类似
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);
}
});
});