Get data from HTTP GET request

I’m sending an HTTP GET request from the client to my server. On the server, I can’t access the data that is passed with the GET request. It works for POST requests but the value is not received in the get request.

The client is Vue.js, and the Server is Express.js in Node.js. The code looks like this.

Client:

var response = await axios.get('/endpoint',{ key: 'value' });

Server:

router.get('/endpoint', async (req,res) => {
    console.log(req.body); // empty
    console.log(req.query);  // empty
    console.log(req.params); // empty
});

I’ve set up my body-parser above. It looks like below

const bodyparser = require('body-parser');
app.use( bodyparser.json() );

How do I access the {key: ‘value’} object that is sent from the client in my server.

Answer

With Axios you can path query params to GET call in 2 different ways:

  1. By putting them into the endpoint path

await axios.get('/endpoint?key=value&key2=value2');

  1. Add them to the config argument in params property object as key-value

await axios.get('/endpoint', { params: {key: 'value', key2: 'value2' }});

Your confusion absolutely makes sense, you try to use same way to pass param for get and post methods, but in Axios these methods have different number of arguments: post(url, data, config), get(url, config)

Let’s return to your example: var response = await axios.get('/endpoint',{ key: 'value' });

So now you can see that { key: 'value' } object that you pass as a second argument is request config and isn’t a data.

You can learn more about request config params here – https://github.com/axios/axios#request-config

Leave a Reply

Your email address will not be published. Required fields are marked *