【问题标题】:Problem with React making Get request to Node(express)React 向 Node 发出 Get 请求的问题(express)
【发布时间】:2020-09-18 06:00:58
【问题描述】:

正如标题所说,我的 react 应用程序的一部分试图从我的数据库中获取一些数据,并根据我传递给它的值进行选择。所以我要继续并首先显示我认为问题所在的代码:

首先,这是我的一个表单向服务器发送请求的函数,我知道代码可能很难看,但我可以从 console.logs 看出我发送的参数是我打算发送的(一个名为“licenciaInput”的字符串

async handleClickLicencia (event) {
        event.preventDefault();
        console.log(this.state);
        console.log("licenciaInput: "+this.state.licenciaInput);
        const datoBuscar = this.state.licenciaInput;

        axios.get('http://localhost:3001/atletas/:licencia',this.state)
            .then(response =>{
                console.log(response)

            })
            .catch(error =>{
                console.log(error)
            })

然后,我在尝试获取“licencia”的 localhost 路由中调用了这个函数,并在我的 postgresql db 中启动了一个选择,其中 licencia="whatever",您可以在代码中看到这句话:

const getAtletasByLicencia = (request, response) => {
   const licencia = request.body.licenciaInput;
   console.log("Request: "+request);
   console.log("what the server gets: "+licencia);
   // const licencia = request.licenciaInput;
   const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
   pool.query(sentencia, (error, results) =>{
        if(error){
            throw error
        }
        response.status(200).json(results.rows)
    })
}

如您所见,我到处都有 console.logs,但我仍然无法访问我发送的任何元素,因为我总是在服务器控制台上获得“未定义”值。

TLDR:如何访问从客户端表单传递到服务器的“licenciaInput”,我尝试过 request.body.licenciaInput、request.params.licenciaInput 和 request.licenciaInput,但这些似乎都不起作用

我也知道我必须在之后处理从服务器接收到的数据,但我需要先解决这个问题,然后再看两步。我对 React 和 node/express 也很陌生,所以请随时用我没有遇到的好的做法来烧我。提前致谢

编辑:我还添加了这段代码,它显示了我的方法在服务器中的路径:

app.get('/atletas/:licencia', db.getAtletasByLicencia)

正如@Gillespie59 建议我应该发送一个 POST 请求,但如果我都尝试向服务器发送参数以进行选择,然后将结果发送回客户端,我认为我不应该这样做

【问题讨论】:

    标签: javascript node.js reactjs postgresql express


    【解决方案1】:

    将您的请求更改为:

    axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
      ...
    
    

    您的路线(如果您使用的是 express)应该如下所示:

    
    app.get('/atletas/:licencia', function (req, res) {
      var licencia = req.params.licencia
      ...
    })
    
    
    

    【讨论】:

    • 你是对的,这是我对其他任何可能会发现这个问题有用的人做错的事情:1:我没有像我一样在获取请求中使用 ${this.state.licenciaInput} :id 因为我是新手。 2:我在路由中请求的参数名称错误,因为它与我定义的不匹配。现在我明白了。
    【解决方案2】:

    当您使用request.body 时,您应该使用 axios 发送一个 POST 请求并添加一个正文。

    【讨论】:

    • 我不相信问题出在这里,因为我试图从服务器检索数据,所以我很确定我应该使用 GET 请求
    • 你使用 const licencia = request.body.licenciaInput;
    • 正如用户 Zirmax 指出的那样,这就是错误所在,我应该编写参数而不是正文,而不是更改请求类型,因为这样我就无法接收服务器从我的使用参数获取请求。
    • 您可以使用带有正文的 POST 或带有参数的 GET。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 2015-07-05
    • 2023-04-04
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多