reactjs - 如何使用 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 元素。之后,我尝试在 useEffect 函数中对 customerList 进行控制台记录setCustomerList(response.data)
,我发现它是一个空对象。
我在这里想念什么?
解决方案
您需要实际从服务器返回结果。目前您只将它们记录到控制台。
就像是
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);
}
});
});
推荐阅读
- git - GIT:如何删除未跟踪的文件“\\”
- matplotlib - Matplotlib 在 Windows 10 上使 Python 崩溃
- python - 如何从 selenium python 中的描述中获取第一个或第三个单词
- java - 防止 Spring Security 通过下一个身份验证提供程序对具有 BadCredentialException 的用户进行身份验证
- asp.net - Change Currency in aspx vb code
- java - Jackson @JsonView annotation interferes with Visibility
- jquery - jQuery how to get paragraph's width in px?
- assembly - x86 assembly works on which CPUs?
- r - 基于三个变量更新虚拟变量
- html - JSF inserts
tag automatically, disturbing the order on page