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.
GET requests do not have bodies
With Axios you can path query params to GET call in 2 different ways:
await axios.get('/endpoint?key=value&key2=value2');
params property object as key-valueawait 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With