Caleb Bird
Caleb Bird

Reputation: 65

Nodejs/Express req.body is Undefined

I have an issue with a post request that suddenly broke and I can't seem to find the issue. In the post form the console.log returns UserID correctly, but within the function the console.log returns Undefined.

Post form:

app.post("/loadTransactions", function(req, res, Data) {
  console.log(req.body.UserID)
  transactions.loadTransactions(req.body.UserID, function(label) {
    Data = label;
    res.send({message: Data});
    })   
  })

Function:

loadTransactions({ UserID }, callback){
        console.log({UserID})
        var sql = `SELECT * FROM MyTable WHERE UserID = ${UserID}`
        var label
        database.Query(sql, function(result){
            label = result[0];
            callback(label)
            });
    }

Client side:

window.onload=function(){
const CreateUser = document.querySelector('.Load');
CreateUser.addEventListener('submit', (e) =>{
    e.preventDefault()
    const UserID = Load.querySelector('.UserID').value
    post('http://1.3.3.7/loadTransactions', {UserID})
})

function post (path, data){
    console.log(data)
    return window.fetch(path,{
        method: 'POST',
        headers: {
            'Accept' : 'application/json',
            'Content-Type': 'application/json'

        },
        body: JSON.stringify(data)
    })
}

}

Upvotes: 0

Views: 505

Answers (1)

towc
towc

Reputation: 2034

In the function, you're destructuring the UserId from the parameter, so you need to pass an object that has a UserId property, or you can chose to not destructure it, and just receive the UserId.

Let's look at a simpler, working, example:

// similarly to your post form
function first(a) {
  console.log(a); // { b: 1 };
  second(a);
}

// similarly to your loadTransactions
function second({ b }) {
  console.log(b); // 1;
  return b + 1;
}

Here's what you're currently doing:

// similarly to your post form
function first(a) {
  console.log(a); // { b: 1 };
  second(a.b);
}

// similarly to your loadTransactions
function second({ b }) { // this tried to load a.b.b
  console.log(b); // undefined;
  return b + 1;
}

As first mentioned, yet another solution is to not destructure at all:

// similarly to your post form
function first(a) {
  console.log(a); // { b: 1 };
  second(a.b);
}

// similarly to your loadTransactions
function second(b) {
  console.log(b); // 1;
  return b + 1;
}

Upvotes: 1

Related Questions