PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 11, 2022

[FIXED] How to send string variable from react to axios

 October 11, 2022     axios, mysql, reactjs     No comments   

Issue

Client side

const recd = props.transGenre // string.. ex) "horror"

useEffect(() => 
  {  
    (async()=>{
      const reqGenre = await axios.get(`./genre`,{recd})
      console.log(reqGenre.data)
      setGenreList2(reqGenre.data)
    })(); 
  },[]);

Server side

app.get('/genre',(req,res)=>{
  console.log('/genre')
  const getGenre = req.params.recd
  console.log(getGenre)
  db.query(`select * from moviedb where genre concat('%','${getGenre}','%')  Order by opendate desc`,(err,data)=>{
      if(!err){
          //console.log(data)
          res.send(data)
          console.log(data)
      }else{
          console.log(err)
      }
  })
})

I want to send a variable to the server's db.query with an axios request in react.

When the above code is executed, '{recd}' delivered from the client is not recognized and undefined is displayed in the console window.

recd is a string variable, and it is used to send a movie genre string to db.query through a click event, put it in a conditional statement, and call a movie with the genre information on the server side.

How can I properly send a string variable ({recd})?


Solution

First ill advice that you properly learn about creating and consuming APIs. Both client and server side code has some issues but can be fixed.

There are two ways you could achieve what you want here. Either you send recd from the client to server using query params or path params.

Ill give the two example below.

Query Params

In the axios request on the client side, change this line from

const reqGenre = await axios.get(`./genre`,{recd})

to

const reqGenre = await axios.get(`/genre?recd=${recd}`)

And on the server side, change this line from

const getGenre = req.params.recd

to

const getGenre = req.query.recd

Path Params

In the axios request on the client side, change this line from

const reqGenre = await axios.get(`./genre`,{recd})

to

const reqGenre = await axios.get(`/genre/${recd}`)

And on the server side, change this line from

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

to

app.get('/genre/:recd',(req,res)=>{
...


Answered By - Oke Tega
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing