0

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)

})

barteg
  • 25
  • 7

1 Answers1

3

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'
    }
})
Kurtis
  • 1,172
  • 2
  • 12
  • 20
  • thanks, I changed it to params, and tried to display it in server console, but still got empty object. – barteg Oct 30 '20 at 11:14
  • 1
    When you say server console, do you mean the console tab in a browsers devs tools? Have you still got you console logs as above: `const {userId} = req.body; console.log(req.body);` as this wont log. You should be able to loo at the network tab and view Headers which will contain the params or the Request URL should display as `http://somewhere.com?userId=USERID` – Kurtis Oct 30 '20 at 11:37
  • By server console I meant one in VSCode, where server was started. yeah I got it. Thank you Kurtis. I didn't think before to just display the entire req in the console to see where the params I provided are. i finally found it, thanks – barteg Oct 30 '20 at 14:10