【问题标题】:React how can you pass a variable to a get request反应如何将变量传递给获取请求
【发布时间】:2022-01-19 22:44:18
【问题描述】:

我正在尝试从teacherId 等于登录人的teacherId 的表中进行查询,但我无法将teacherId 从前端传递到后端.

这是后端

app.get("/api/get", async(req,res) => {
    const teacherId = req.body.teacherId
    connection.query(
        "SELECT class FROM homework WHERE teacherID = ?",
        [teacherId],
        (err, result) => {
            if (result){
                res.send({ message: result })
            } else{
                console.log(err)
            }
        }
    )
})

这是前端

 useEffect(() => {
        Axios.get("http://localhost:1337/api/get", {
            teacherId: teacherId
        }).then((response) => {
            if(response){
                setDisplayHomework(response.data.message)
            } else{
                console.log("error")
            }
        })
    })
const teacherId = localStorage.getItem("teacherId")

我认为问题出在teacherId: teacherId 上,但我不知道为什么。

【问题讨论】:

  • 您要在网址中发送param 吗?
  • @Alessandro 不,我想将变量teacherId从前端传递到后端

标签: javascript node.js reactjs express axios


【解决方案1】:

你需要使用

Axios.get("http://localhost:1337/api/get", {
     params: { teacherId }
 });

并使用req.query.teacherId 阅读它


如果您看到Axios.get 签名,那就是

axios.get(url[, config])

对比

axios.post(url[, data[, config]])

将数据作为第二个参数传递。

那是因为GET 请求中的正文没有被服务器使用。阅读HTTP GET with request body了解更多信息。

【讨论】:

  • 谢谢,这对我有很大帮助,我对此很陌生
【解决方案2】:

通常您不会发送带有获取请求的正文。将教师 ID 放入 url。然后这称为路径变量。

app.use('/teacher/:teacherId', function(req, res, next) {
  console.log(req.params.teacherId);
  next();
})

【讨论】:

    【解决方案3】:

    Get 请求不像 post 请求那样有请求主体,因此 Axios.get 函数不应该有第二个主体参数。而是将参数作为 url 传递,如下所示:

    useEffect(() => {
            Axios.get("http://localhost:1337/api/get?teacherId="+teacherId).then((response) => {
                if(response){
                    setDisplayHomework(response.data.message)
                } else{
                    console.log("error")
                }
            })
        })
    

    然后在您的后端代码中使用 req.params 来访问获取请求的 url 参数:

    app.get("/api/get", async(req,res) => {
        const teacherId = req.params.teacherId
        connection.query(
            "SELECT class FROM homework WHERE teacherID = ?",
            [teacherId],
            (err, result) => {
                if (result){
                    res.send({ message: result })
                } else{
                    console.log(err)
                }
            }
        )
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-24
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      相关资源
      最近更新 更多