barteg
barteg

Reputation: 25

Axios get function sends empty request

im doing a simple MERN blog-project, trying to learn new things. I've already made server, and now working with client side. I've tested endpoints with Postman, and they're working correctly. The problem is on the client side with axios.

const sensorResponse = await axios({
        method: 'get',
        url: url,
        headers: {"X-Auth-Token": localStorage.getItem('auth-token'),
        "content-type": "application/json" },
        data : {
            userId: user.id
        }
    })

and the get end point

router.get('/', auth, async (req,res)=>{
 const {userId} = req.body;
 console.log(req.body);
 console.log(userId);
 const blogs = await Blog.find({userId:userId})
 res.json(blogs)
 })

authorization is correct, console.log in the "auth" function displays and verifies the token correctly. unfortunately get endpoint displays req.body as empty object in console. I've tried another request function:

const blogResponse = await axios.get(url,data,headers)

but it works the same... could you guys suggest me how should this request look like?

///// EDIT SOLVED PROBLEM

const sensorResponse = await axios({
        method: 'get',
        url: url,
        headers: {"x-auth-token": localStorage.getItem('auth-token'),
        "content-type": "application/json" },
        params: {
            'userId': user.id
        }
    })

and to get the userId passed with params in request, endpoint should look like:

router.get('/', auth, async (req,res)=>{
  const userId = req.query.userId;
   console.log(userId)
   const blogs= await Blog.find({userId:userId})
  res.json(blogs)

})

Upvotes: 0

Views: 1680

Answers (1)

Kurtis
Kurtis

Reputation: 1282

GET requests don't have a data or body. Check this answer here

TLDR

axios({
    method: 'GET',
    url: `http://localhost:4444/next/api`,
    params: {
       id: 'id'
    }
})

Upvotes: 3

Related Questions