Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React how can you pass a variable to a get request

I’m trying to query from a table where the teacherId is equal to the teacherId of the person that logs in but i can’t pass that teacherId from the front end to the back end.

This is the back end

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

This is the front end

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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")

I think the problem lies where it says teacherId: teacherId but i don’t why.

>Solution :

You need to use

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

and use req.query.teacherId to read it


If you see the Axios.get signature it is

axios.get(url[, config])

in contrast to

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

which passes the data as the second argument.

That is because the body in GET requests is not used by the servers. Read HTTP GET with request body for more on this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading