Akhilesh Chobey Akhilesh Chobey - 1 month ago 5
Node.js Question

Express app.get: req.body returns type of value and not the actual value

I am quite novice to Express and working on a project. I have 4 radio buttons which represent user answer. I have stored the correct answers in a MongoLabs database which I retrieve and log in the

app.get()
function. I want to check the user answer against those correct answers. However when I log
req.body
I get
[object Object]


index.html:

<!DOCTYPE html>
<head>
<title>Online Testing Website</title>
</head>
<body>
<div id="question">
<p>This is my first question</p>
<br>
</div>
<div id="answer">
<form action="/answer" method="get">
<input id="a" type="radio" name="ans" value="A" >A<br>
<input id="b" type="radio" name="ans" value="B" >B<br>
<input id="c" type="radio" name="ans" value="C" >C<br>
<input id="d" type="radio" name="ans" value="D" >D<br><br><br>
<button type="submit">Submit</button>
</form>
</div>

<script type="text/javascript" src="./server.js"></script>

</body>
</html>


server.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
var path = require('path');
var mongo = require('mongodb').MongoClient;

app.use(bodyParser.urlencoded({extended: true}));

var db;

app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

mongo.connect('mongodb://deodhar:deodhar@ds015636.mlab.com:15636/correct-answers', function (err, database) {
if(err){
return console.log('mongo connect if: ' + err);
}
db = database;
app.listen(8080, function () {
console.log("Listening on 8080");
});
});


app.get('/answer', function (req,res) {
console.log("User answer: " + req.body);
var cursor = db.collection('answers').find().toArray(function (req,result) {
console.log(result);
res.redirect('/');
});
});

Answer

With GET requests, there won't be a req.body; use req.query instead.

Also, if you want to log the contents of an object, don't use string concatenation (using +), but pass the object as a separate argument to console.log (using ,):

console.log("User answer: ", req.query);