Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to an API get request in react.js

I wonder is there a way to pass a parameter from the client to the back-end API get Request. At this moment I hard coded the needed argument (name:"newName").

back-end route:

app.get('/api/get/beerWithComments', (req,res,next) =>{



    Beer.findOne({name:'newName'}) //I want to pass the correct name, now it's hard coded.
        .populate('comments').exec((err,beer) =>{
            if(err) return next(err);
            res.json(beer);
        });

});

My action method:

  export const fetchBeerWithComments =() => async dispatch => {
    const res= await axios.get('/api/get/beerWithComments');
    dispatch({type: FETCH_BEER_WITH_COMMENTS, payload : res.data });

}

I thought to pass the parameter here in. But I don't know if I can pass the argument to my back-end.

export const fetchBeerWithComments =(parameter) => async dispatch => {...
like image 292
Dave_888 Avatar asked May 09 '26 01:05

Dave_888


1 Answers

You can pass the parameter name in the query string and read the parameter value in handler using req.query like

app.get('/api/get/beerWithComments', (req, res, next) =>{
  var qname = req.query.name || "";
  if(!qname.length) {
    res.status(404).json({"msg": 'Invalid name in query string'});
    res.end();
    return;
  }
  Beer.findOne({name: qname}) //I want to pass the correct name, now it's hard coded.
    .populate('comments').exec((err,beer) =>{
        if(err) return next(err);
        res.json(beer);
    });
});

And while calling GET API from the client side just add query string param name with respective value and it should work as you expected. for eg URL will be like

export const fetchBeerWithComments =(parameter) => async dispatch => {
  const res= await axios.get('/api/get/beerWithComments?name=' + parameter);
  dispatch({type: FETCH_BEER_WITH_COMMENTS, payload : res.data });
}
like image 175
Suresh Prajapati Avatar answered May 11 '26 00:05

Suresh Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!