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})?
CodePudding user response:
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)=>{
...