【问题标题】:How to get a variable from Frontend to the Backend using get API in reactjs with Express API如何使用带有 Express API 的 reactjs 中的 get API 从前端获取变量到后端
【发布时间】:2021-11-07 10:51:03
【问题描述】:

我想从我的货运表中获取信息,以便处理我需要在前端处理的其他信息。但是我不知道如何使用Axios.get()方法来获取登录用户的电子邮件来查询我的MySQL数据库。

在我的前端,我定义了一个已登录电子邮件的 useState,并将其设置为当前登录的用户。如何使用 GET 方法将其传递给我的后端?

这是我的代码:

服务器:

app.get('/api/freightID', (req, res) => {

    const email = req.body. //how would i get the email from the front end to use it in my query?
    db.query("SELECT * FROM freight_shipment WHERE user_email = ?", email, (err, result) => {
        if(err){
            console.log(err)
        }
        if(result.length > 0 ){
            res.send(result);
        }
    });
});

前端:

const [loggedEmail,setLoggedEmail] = useState("");
    Axios.defaults.withCredentials = true;
    useEffect(() => {
        Axios.get('http://localhost:3001/login').then((response) => {

            if(response.data.loggedIn == true){
                setLoggedEmail(response.data.user[0].email)
                setLoginStatus(response.data.loggedIn);
                console.log(response.data.loggedIn)
            }
        })
    },[]);

useEffect(() => {
        Axios.get("http://localhost:3001/api/freightID").then((response) => {
            console.log(response);
        })
    });

【问题讨论】:

    标签: javascript mysql node.js reactjs express


    【解决方案1】:

    Axios.get 中有一个 config 对象,您可以将参数放在那里以将它们发送给 BE

    你会这样使用它:

    Axios.get("http://localhost:3001/api/freightID", {
      params: { email: loggedEmail },  //<-- Put params here
    }).then((response) => {
      console.log(response);
    });
    

    然后在你的 BE 中,你会得到这样的结果:

    app.get('/api/freightID', (req, res) => {
    
        const email = req.query.email //<-- It's here in the req.query
        db.query("SELECT * FROM freight_shipment WHERE user_email = ?", email, (err, result) => {
            if(err){
                console.log(err)
            }
            if(result.length > 0 ){
                res.send(result);
            }
        });
    });
    

    【讨论】:

      【解决方案2】:

      您可以将loggedEmailin Get 作为查询参数或路径参数传递。

      请看这篇文章。 https://masteringjs.io/tutorials/axios/get-query-params.

      在你的情况下,你可以这样做:

      const params = {
        loggedInUserEmail: loggedEmailin 
      };
      Axios.get(`http://localhost:3001/api/freightID/{params.loggedInUserEmail}`)
      

      在服务器端你可以获得价值

      app.get('/api/freightID/:email', (req, res) => {}) etc ... ///
      
      var end = req.params['email']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-09
        • 2022-01-27
        相关资源
        最近更新 更多