首页 > 解决方案 > 如何使用 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),我发现它是一个空对象。

我在这里想念什么?

标签: reactjsaxiosreact-hooksuse-effect

解决方案


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

就像是

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);
    }
  });
});

推荐阅读