1

My frontend code:

const user = useSelector(selectUser)
function getWatchLater(name){
  axios.get('http://localhost:5000/watchlater', {user:name})
  .then((response)=>{
    // console.log(response.data)
    setWatchLater(response.data)
  })
}

The user variable holds the username and the function sends that username to the backend to get the data. Don't worry, the user variable does hold the username, i have checked it thoroughly.

My backend code:

const mysql = require('mysql2')
const express = require('express')
const cors = require('cors');


const app = express()
app.use(cors());
app.use(express.json())

app.get("/watchlater", (request, response)=>{
    const user = request.body.user;
    //console.log(user);
});

So basically, it will get the username and run the query. The problem is it does not get the username at all from the frontend. I tried console logging the variable user but to no avail. It returns empty.

  • I tired putting the functions in the frontend in a useEffect hook but it does not work either. – MUHAMMADMOAAZ SIDDIQUI Jul 26 '22 at 15:42
  • You can [edit] your post if you need to add more info. Your express route never responds to the request (and yes, the frontend should be in a useEffect or you'll probably get an infinite loop). There's no payload for GET requests--add the information to the query parameters or path. I suggest a basic express/ReactJS tutorial which will surely cover these things. – ggorlen Jul 26 '22 at 15:44
  • 2
    A GET request doesn't generally have a body - the semantics aren't defined, and the second argument to `axios.get` is **not** the request body. – jonrsharpe Jul 26 '22 at 15:44
  • Your `getWatchLater` function runs an infinite loop. – Tyler2P Jul 26 '22 at 16:40

2 Answers2

1

The second argument in the axios.get() function is expecting a config object. Checkout the axios documentations on instance method and request config.

In short, in the frontend part, pass your payload into the data field of the config object, as shown in the example below.

const config = {
  headers: { Authorization: token },
  data: { user:name }
}
const response = await axios.get(`${url}`, config)
samuelthien
  • 59
  • 1
  • 4
0

You need to send parameter using params object of config in case of get request. Your frontend request should change to this,

const user = useSelector(selectUser)
function getWatchLater(name){
  axios.get('http://localhost:5000/watchlater', { params: { user: name }
}).then((response)=>{
    // console.log(response.data)
    setWatchLater(response.data)
  })
}

In your express endpoint you should receive it as,

app.get("/watchlater", (request, response)=>{
    const user = request.params.user;
    //console.log(user);
});
Abhishek Singh
  • 408
  • 1
  • 5