【问题标题】:Is it possible to make a dynamic GET request with Axios params?是否可以使用 Axios 参数进行动态 GET 请求?
【发布时间】: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 数据库,有时还需要不止一个输入。

【问题讨论】:

    标签: reactjs api axios


    【解决方案1】:

    您可以使用有状态变量并确保您的效果依赖于它来运行。在这种情况下,我使用的是 name 变量。您可以使用setName 更改name 变量的值,您的效果将重新运行。

    const [name, setName] = useState("Timmy Test")
    
    useEffect(() => {
      axios
        .get("http://localhost:4000/customer/lookup", {
          params: { name }
        })
        .then((response) => {
          setCustomerList(response.data);
          console.log(customerList);
        });
    }, [name]);
    

    【讨论】:

    • 我认为这解决了一个问题,但是我如何在服务器端访问该名称参数?
    • 您应该可以在req.params.name 获得它,如果可行,请告诉我!
    • 在不更改 axios.get("http://localhost:4000/customer/lookup", { name: "Timmy Test" }) 的情况下,我将服务器端的代码更新为 const name = req.params.name;,但这不起作用。还有其他想法吗?
    • @cchau 哎呀,看起来 axios 需要格式化为 { params: { name: "Timmy Test" } } 的参数。我更新了我的回复,试一试!
    • 刚查了一下,其实是在查询参数里面,试试req.query.name
    猜你喜欢
    • 2020-02-19
    • 2022-12-17
    • 2018-12-10
    • 2016-08-26
    • 2022-01-04
    • 2022-01-16
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多