Source:  Twitter logo

I am running a react app with nodejs on backend. Whenever I make an axios call without parameters, everything works, but when I try to add paramaters and use them with req.body.variableName, it prints undefined. Printing req.body is just an empty curly brace so somehow my data is not being sent.

React File with axios call

getFriendCount(){
    var data = {
        UserID: this.state.UserID,
    }
    console.log(data)
    axios.get("http://localhost:8081/getFriendCount", data).then((response)=>{
        if (response.status >= 400) {
            console.log(response.status);
            throw new Error("Bad response from server");
        } else{
            return response.data[0].friendCount
        }
    }).then((data)=>{
        console.log(data)
        this.setState({count: data})
    })
}

serversql.js

const HTTP_PORT = process.env.PORT || 8081;
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const cors = require("cors");
const mysql = require('mysql');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const {addNewMemory,getAllMemories, getFriendCount} = require('./db-services.js');

//Database connection...

app.get('/data', getAllMemories);
app.post('/addMemory',urlencodedParser,addNewMemory);
app.get('/getFriendCount',urlencodedParser, getFriendCount);

app.listen(HTTP_PORT, ()=>{console.log("API listening on: " + HTTP_PORT)});

db-services.js (req.body.UserID is undefined)

module.exports={
  getFriendCount:(req,res) => {
    console.log(req.body)        //empty curly brace
    console.log(req.body.UserID) //undefined
    console.log(req.params)      //empty curly brace
    var sql = "SELECT COUNT(*) AS friendCount FROM friendship WHERE UserId1 = (?) OR UserId2 = (?)";
    var values = [req.body.UserID, req.body.UserID]
    dbconnection.query(sql, values, function(err,result,fields){
        if(err){
            return res.status(500).send(err);
        } else {
            res.send(result);
        }
    })
},
}

In the Axios.get(), the data represent the params not body data. So please use the req.params instead the body. And then node you use the route that way.

app.get('/getFriendCount/:Id',urlencodedParser, getFriendCount);

And then please get the Id using below.

console.log(req.params.Id);

And then you need to change your API like this.

axios.get(`http://localhost:8081/getFriendCount/${this.state.UserID}`)

Please try this.

4 users liked answer #0dislike answer #04
Lion profile pic
Lion

try the following in the client side

  axios.get("http://localhost:8081/getFriendCount", {
          params: {
            UserID: yourUserID
          }
        }).then((response)=>{
        if (response.status >= 400) {
            console.log(response.status);
            throw new Error("Bad response from server");
        } else{
            return response.data[0].friendCount
        }
    }).then((data)=>{
        console.log(data)
        this.setState({count: data})
    })

and in the server side instead of using the body use the query like this console.log(req.query.UserID). Hope this helps :)

3 users liked answer #1dislike answer #13
user8572385 profile pic
user8572385

If you want to send a body you can't use a GET method. Only a POST or a PUT method should be used in this case. GET methods will only take param and query, where `params can be used like this:

app.get('/getFriendCount/:id', handler);

if you would call /getFriendCount/123, req.param.id would return 123

and query could be used like this:

/getFriendCount?name=pedro - req.query would yield { name:"pedro" }

1 users liked answer #2dislike answer #21
pedrosimao profile pic
pedrosimao

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).