How to pass a localstorage value as an argument in axios request

I have a React app and I use Express to handle my db queries.

What I want is to pass my user id stored in localstorage into a post request.

(My app is basically a game where users can gain cards to fight against other players, and to do so, I need to update my db when a user receives a card, which is why I’m trying to do the following).
Here’s my code:

import React, {useEffect, useState} from 'react';
import Axios from "axios";
import axios from "axios";

const Cards = () => {

const [card, setCard] = useState([]);
const id = localStorage.getItem("id");
console.log(id) // Output is 1 (correct)

useEffect(() => {
    async function fetchData() {
        try {
            // Below, id should refer to localStorage.getItem("id")
            const res = await Axios.post('http://localhost:3001/getRandomCard', {id}) 
            setCard(res.data)
        } catch (err) {
            console.log('error:', err)
        }
    }

    fetchData()
}, []);

return (
    <div>
        <div>
            {card.map(aCard => <div className={"text-center"} key={aCard.name}> {aCard.name}
                <img alt={"Image de " + aCard.name} className={'activator'} src={'http://localhost/lfl/inc/img/players-ico/' + aCard.name} style={{width: '100%'}}/>
            </div>)}
        </div>

    </div>);
};

export default Cards;

And on my app.js:

app.post('/getRandomCard', async function (req, res) {

    const id = req.params.id;

    console.log('userid= ', id) // Output: undefined

    // ...

})

I’m very new to React, so I’m trying basic stuff, and maybe my code is not the better way to do what I’m actually trying to do, if so, every comment is deeply appreciated.

>Solution :

With the post method, on the second place is object with ‘body’ of the request. So your data is not in the params, but its in the body.

So you have to use

 const id = req.body.id;

instead of

const id = req.params.id;

Leave a Reply