Axios get in url works but with second parameter as object it doesn't

ReactjsReact NativeReduxAxios

Reactjs Problem Overview


I'm trying to send GET request as second parameter but it doesn't work while it does as url.

This works, $_GET['naam'] returns test:

export function saveScore(naam, score) {
  return function (dispatch) { 
    axios.get('http://****.nl/****/gebruikerOpslaan.php?naam=test')
      .then((response) => {
        dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
      })
  }
};

But when I try this, there is nothing in $_GET at all:

export function saveScore(naam, score) {
  return function (dispatch) { 
    axios.get('http://****.nl/****/gebruikerOpslaan.php',
    {
    	password: 'pass',
    	naam: naam,
    	score: score
    })
      .then((response) => {
        dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
      })
  }
};

Why can't I do that? In the docs it clearly says it's possible. With $_POST it doesn't work either.

Reactjs Solutions


Solution 1 - Reactjs

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

Solution 2 - Reactjs

On client:

axios.get('/api', {
  params: {
    foo: 'bar',
  },
});

On server:

function get(req, res, next) {
    
  let param = req.query.foo
  // ...
}

Solution 3 - Reactjs

For me I was trying to send params using axios.post.

When switch both client and server to axios.get, req.query.foo worked like a charm

Solution 4 - Reactjs

This works fine for me. When it is post request nested data object isn't needed but in get requests, in order to send data, you need it.

axios.get('/api', {
    data: {
        foo: 'bar'
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSinan SametView Question on Stackoverflow
Solution 1 - ReactjsNick UraltsevView Answer on Stackoverflow
Solution 2 - ReactjsdanikorenView Answer on Stackoverflow
Solution 3 - ReactjscormacncheeseView Answer on Stackoverflow
Solution 4 - ReactjsNika NishnianidzeView Answer on Stackoverflow