Home > Enterprise >  Can't get response body in Axios with express
Can't get response body in Axios with express

Time:07-27

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.

CodePudding user response:

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)

CodePudding user response:

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);
});
  • Related