Im creating a web application that should send info from the client side to the server side every time a specific button is pressed. When I press the button, the terminal continues to tell me that the value I am trying to pass through the post request body is undefined.

Client side code (Where button is called from) -

function upvote(elem) {
  var parentID = elem.parentNode.id;
  console.log('Upvote button was clicked' + parentID);

  fetch('/upvote', {     //This is called to pass the body data to server side code
    method: 'post',
    body: JSON.stringify({
      id: parentID
    })
  })
  .then(function(res) {
    if(res.ok) {
      console.log('Click was recorded');
      return;
    }
    throw new Error('Request failed.');
  })
  .catch(function(error) {
    console.log(error);
  });
}

function downvote(elem){
  var parentID = elem.parentNode.id;
  console.log('Downvote button was clicked');

  fetch('/downvote', {  //This is called to pass the body data to server side code
    method: 'POST',
    body: JSON.stringify({
      id: parentID })
  })
  .then(function(res) {
    if(res.ok) {
      console.log('Click was recorded');
      return;
    }
    throw new Error('Request failed.');
  })
  .catch(function(error) {
    console.log(error);
  });
}

setInterval(function() {
  fetch('/ranking', {method: 'GET'})
    .then(function(response) {
      if(response.ok) return response.json();
      throw new Error('Request failed.');
    })
    .then(function(data) {

    })
    .catch(function(error) {
      console.log(error);
    });
}, 1000);

My app.js (Server side code) --

const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();

const {getLoginPage, login} = require('./routes/index');    
const {players, questionsPage, upvoteQues, downvoteQues, ranking, addQuestionsPage, addQuestion, deleteQuestion, editQuestion, editQuestionPage} = require('./routes/question');  //All my routes
const port = 5000;

const db = mysql.createConnection ({
    host: 'localhost',
    user: 'root',
    password: '',
    database: ''
});

// connect to database
db.connect((err) => {
    if (err) {
        throw err;
    }
    console.log('Connected to database');
});
global.db = db;

// configure middleware
app.set('port', process.env.port || port); port
app.set('views', __dirname + '/views'); folder to render our view
app.set('view engine', 'ejs'); 
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); 
app.use(express.static(__dirname + '/public'));




app.get('/', getLoginPage);
app.get('/questions', questionsPage);
app.get('/add', addQuestionPage);
app.get('/edit/:id', editQuestionPage);
app.get('/delete/:id', deleteQuestion);
app.get('/ranking', ranking);
app.post('/', login);
app.post('/add', addQuestion);
app.post('/edit/:id', editQuestion);
app.post('/upvote', upvoteQues);     //This is then used 
app.post('/downvote', downvoteQues);  //This is then used 


// set the app to listen on the port
app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
});

My question.js (More server side code, just separated into a different file)

const fs = require('fs');

module.exports = {
    questionsPage:(req, res) =>{
        let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC"; 

        db.query(query, (err, result) => {
            if (err) {
                console.log('Query error');
                res.redirect('/');
            }
            res.render('questions.ejs', {
                title: "JustAsk!",   
                questions: result,
            });
        });
    },
    upvoteQues: (req, res) => {
        console.log(req.body.id);       //Error here
        let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'"      //Error here
        db.query(updateQuery, (err, result) => {
            if(err){
                console.log('Query error');
                res.redirect('/players')
            }
        });
    },
    downvoteQues: (req, res) =>{
        console.log(req.body.id);      //Error here
        let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'"       //Error here
        db.query(updateQuery, (err, result) => {
            if(err){
                console.log('Query error');
                res.redirect('/players')
            }
        });
    }, 
    ranking: (req, res) => {
        let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC"; 
        db.query(query, (err, result) => {
            if (err) {
                console.log('Query error');
            }
            res.send(result);
        });
    }
};

1 Answers

0
Narayan Sharma On Best Solutions

The body should be in JSON format, not a string.

 body: JSON.stringify({
      id: parentID 
})

change to:

 body: { id: parentID }

and content type should be 'application/json` like below.

fetch('/url', {
    method: 'POST',
    body: {id: parentID },
    headers: {
            "Content-Type": "application/json",
    }
  })