Dave_888
Dave_888

Reputation: 433

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 => {...

Upvotes: 3

Views: 17311

Answers (2)

Suresh Prajapati
Suresh Prajapati

Reputation: 4457

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

Upvotes: 5

Rcc27
Rcc27

Reputation: 11

If you need to pass it back you could just change the api endpoint to have a dynamic parameter e.g change the get endpoint to:

/api/get/beerWithComments/:beerName

So on the front end you can have

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

And then on the backend

app.get('/api/get/beerWithComments/:beerName', (req,res,next) =>{
    Beer.findOne({name: req.params.beerName})
        .populate('comments').exec((err,beer) => {
            if(err) return next(err);
            res.json(beer);
     });
});

Upvotes: 1

Related Questions